/* ============================================================
   ASISTENTE CON HACIENDA — entender y responder notificaciones AEAT
   Additive: reutiliza extractPdfText() de review.jsx + callLexly.
   ============================================================ */

const HACIENDA_SYSTEM = 'Eres un experto en procedimientos tributarios españoles. El usuario ha recibido una comunicación de la AEAT y necesita entenderla. Analiza el documento e identifica: el tipo de comunicación, qué pide exactamente Hacienda (en lenguaje claro y sencillo), el plazo de respuesta, las consecuencias de no responder, y las opciones del usuario. Sé claro, calmado y práctico. Destaca siempre el plazo, porque es crítico. Si la situación es compleja o las cantidades son importantes, recomienda con claridad acudir a un asesor fiscal o gestor antes de responder. Nunca minimices un requerimiento serio ni generes alarma innecesaria. Tu objetivo es que el usuario entienda su situación y sepa cómo actuar.';

function parseHacienda(raw) {
  const map = {};
  if (!raw) return map;
  const re = /\[\[([A-Z_]+)\]\]/g;
  const parts = []; let m;
  while ((m = re.exec(raw))) parts.push({ key: m[1], start: m.index, end: re.lastIndex });
  for (let i = 0; i < parts.length; i++) {
    const p = parts[i];
    if (p.key === 'FIN') continue;
    const next = parts[i + 1] ? parts[i + 1].start : raw.length;
    map[p.key] = raw.slice(p.end, next).replace(/\[\[FIN\]\]/g, '').trim();
  }
  return map;
}

async function analyzeNotification(text) {
  const prompt = `Analiza esta comunicación recibida de la Agencia Tributaria (AEAT) y ayuda al usuario a entenderla. Usa EXACTAMENTE estos marcadores, cada uno en su línea seguido del contenido:
[[TIPO]] (tipo de comunicación: requerimiento de información, propuesta de liquidación, sanción, comprobación limitada, diligencia de embargo, providencia de apremio, etc.)
[[PLAZO_TEXTO]] (el plazo de respuesta tal cual, ej. "10 días hábiles desde la notificación")
[[PLAZO_DIAS]] (solo el número aproximado de días naturales/hábiles de plazo, un entero; si no se puede determinar, escribe NA)
[[PIDEN]] (qué pide exactamente Hacienda, en lenguaje claro y sencillo; usa viñetas "-" si hay varias cosas)
[[CONSECUENCIAS]] (qué pasa si no respondes en plazo)
[[OPCIONES]] (las opciones del usuario; viñetas "-")
[[PASOS]] (pasos recomendados concretos; viñetas "-")
[[GRAVEDAD]] (alta | media | baja — alta si hay sanción elevada, propuesta de liquidación importante o procedimiento complejo)

Reglas: lenguaje claro y calmado; no minimices un requerimiento serio ni generes alarma. Si no hay texto suficiente para analizar, indícalo en [[PIDEN]]. Cuando termines, escribe [[FIN]].

DOCUMENTO RECIBIDO:
"""
${text.slice(0, 8000)}
"""`;
  const messages = [{ role: 'user', content: prompt }];
  let full = '';
  for (let seg = 0; seg < 4; seg++) {
    const chunk = await callLexly(messages, HACIENDA_SYSTEM, 3000);
    const done = /\[\[FIN\]\]/.test(chunk);
    full += (full ? '\n' : '') + chunk.replace(/\[\[FIN\]\]/g, '').replace(/\s+$/, '');
    if (done) break;
    if (chunk.length < 500) break;
    messages.push({ role: 'assistant', content: full });
    messages.push({ role: 'user', content: 'Continúa donde lo dejaste, sin repetir. Cuando termines, añade [[FIN]].' });
  }
  return parseHacienda(full);
}

async function generateResponseDraft(text, analysis) {
  const prompt = `Redacta un BORRADOR de escrito de respuesta / alegaciones para presentar ante la AEAT, en respuesta a esta comunicación (tipo: ${analysis.TIPO || 'comunicación AEAT'}). Lo que piden es: ${(analysis.PIDEN || '').slice(0, 800)}.

El escrito debe incluir: encabezado dirigido a la AEAT, datos a rellenar por el interesado (NIF, nombre, domicilio) entre corchetes, referencia al expediente/notificación entre corchetes, cuerpo con la exposición y/o aportación de lo solicitado, solicitud final, y lugar/fecha/firma. Tono formal y correcto. Usa [corchetes] para los datos que el usuario debe completar. Devuelve solo el texto del escrito, sin comentarios.`;
  return await callLexly(prompt, 'Eres un experto en derecho tributario español que redacta escritos formales de respuesta y alegaciones ante la AEAT. Devuelves únicamente el texto del escrito, formal y bien estructurado, con [corchetes] para los datos a completar.', 3000);
}

const GRAV_HAC = {
  alta:  { c: 'var(--red)',   bg: 'var(--red-dim)',   label: 'Situación seria' },
  media: { c: 'var(--amber)', bg: 'var(--amber-dim)', label: 'Atención' },
  baja:  { c: 'var(--green)', bg: 'var(--green-dim)', label: 'Gestión ordinaria' },
};

function AsistenteHacienda() {
  const [text, setText] = useState('');
  const [fileName, setFileName] = useState('');
  const [dragOver, setDragOver] = useState(false);
  const [reading, setReading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [analysis, setAnalysis] = useState(null);
  const [error, setError] = useState(null);
  const inputRef = useRef(null);

  // borrador
  const [draft, setDraft] = useState('');
  const [draftLoading, setDraftLoading] = useState(false);
  const [proRequested, setProRequested] = useState(false);

  const handleFile = async (file) => {
    if (!file) return;
    setError(null); setFileName(file.name); setReading(true);
    try {
      if (file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf')) {
        const t = await extractPdfText(file);
        if (!t) throw new Error('empty');
        setText(t);
      } else if (file.type.startsWith('image/')) {
        throw new Error('image');
      } else {
        setText(await file.text());
      }
    } catch (e) {
      setFileName('');
      setError(e.message === 'image'
        ? 'Por ahora no puedo leer imágenes escaneadas automáticamente. Pega el texto de la notificación manualmente.'
        : e.message === 'empty'
          ? 'No se ha podido extraer texto de este PDF (puede ser una imagen escaneada). Pega el texto manualmente.'
          : 'No se ha podido leer el archivo. Pega el texto manualmente.');
    } finally { setReading(false); }
  };

  const onDrop = (e) => { e.preventDefault(); setDragOver(false); const f = e.dataTransfer.files?.[0]; if (f) handleFile(f); };

  const analyze = async () => {
    if (!text.trim() || loading) return;
    setError(null); setLoading(true); setAnalysis(null); setDraft('');
    try {
      const res = await analyzeNotification(text);
      if (!res || !Object.keys(res).length) throw new Error('parse');
      setAnalysis(res);
    } catch (e) {
      setError(e.message === 'NO_API' ? 'No se ha podido conectar con el servicio. Revisa tu conexión e inténtalo de nuevo.' : 'No se ha podido analizar la notificación. Inténtalo de nuevo.');
    } finally { setLoading(false); }
  };

  const makeDraft = async () => {
    setDraftLoading(true); setDraft('');
    try {
      const d = await generateResponseDraft(text, analysis);
      setDraft(d);
    } catch (e) {
      setError('No se ha podido generar el borrador. Inténtalo de nuevo.');
    } finally { setDraftLoading(false); }
  };

  const downloadDraft = () => {
    const w = window.open('', '_blank'); if (!w) return;
    w.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Respuesta AEAT</title><style>@page{margin:2.2cm}body{font-family:'Times New Roman',Georgia,serif;font-size:12pt;line-height:1.6;color:#111;max-width:720px;margin:0 auto}pre{white-space:pre-wrap;font-family:inherit;font-size:12pt}</style></head><body><pre>${draft.replace(/</g,'&lt;')}</pre></body></html>`);
    w.document.close(); setTimeout(() => w.print(), 350);
  };

  const reset = () => { setText(''); setFileName(''); setAnalysis(null); setError(null); setDraft(''); setProRequested(false); };

  const grav = analysis && (GRAV_HAC[(analysis.GRAVEDAD || '').toLowerCase().trim()] || null);
  const dias = analysis && analysis.PLAZO_DIAS && /^\d+$/.test(analysis.PLAZO_DIAS.trim()) ? parseInt(analysis.PLAZO_DIAS.trim(), 10) : null;

  return (
    <div className="section-pad fade-up">
      <div className="eyebrow">Procedimientos AEAT</div>
      <h1 className="h-title">Asistente con Hacienda</h1>
      <p className="h-sub">¿Has recibido una carta de Hacienda? Te ayudo a entender qué te piden y a preparar tu respuesta, paso a paso. Con calma.</p>

      <div className="hac-disclaimer">
        <Icon name="shield" size={16} />
        <span>Este asistente te ayuda a entender y preparar tu respuesta, pero <b>no sustituye a un asesor fiscal o gestor colegiado</b>. Para requerimientos importantes, consulta siempre con un profesional antes de responder. Recuerda: los plazos con Hacienda son <b>improrrogables y críticos</b>.</span>
      </div>

      {!analysis && (
        <div className="hac-input fade-up">
          <div
            className={'dropzone' + (dragOver ? ' over' : '') + (text ? ' has-text' : '')}
            onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
            onDragLeave={() => setDragOver(false)}
            onDrop={onDrop}
            onClick={() => !text && inputRef.current?.click()}
          >
            <input ref={inputRef} type="file" accept=".pdf,.txt,.md" hidden onChange={(e) => handleFile(e.target.files?.[0])} />
            {reading ? <div className="dz-center"><Spinner /><p>Extrayendo texto…</p></div>
              : fileName ? (
                <div className="dz-file">
                  <div className="dz-file-ic"><Icon name="mail" size={20} /></div>
                  <div className="dz-file-meta"><strong>{fileName}</strong><span>{text.length.toLocaleString('es-ES')} caracteres</span></div>
                  <button className="icon-btn" onClick={(e) => { e.stopPropagation(); reset(); }}><Icon name="x" size={15} /></button>
                </div>
              ) : (
                <div className="dz-center">
                  <div className="dz-ic"><Icon name="upload" size={24} /></div>
                  <p className="dz-title">Sube la notificación (PDF) o <span>haz clic</span></p>
                  <p className="dz-sub">PDF o texto · también puedes pegarlo abajo</p>
                </div>
              )}
          </div>

          <div className="rev-or"><span>o pega el texto de la carta</span></div>
          <textarea className="textarea hac-textarea" rows={7} placeholder="Pega aquí el contenido de la notificación de Hacienda…" value={text} onChange={(e) => { setText(e.target.value); if (fileName) setFileName(''); }} />

          {error && <ErrorNote>{error}</ErrorNote>}

          <div className="hac-actions">
            {text && <button className="btn btn-ghost" onClick={reset}>Limpiar</button>}
            <button className="btn btn-primary" disabled={!text.trim() || loading} onClick={analyze}>
              {loading ? <><Spinner /> Analizando…</> : <><Icon name="sparkle" size={16} /> Entender mi notificación</>}
            </button>
          </div>
        </div>
      )}

      {loading && !analysis && (
        <div className="hac-loading fade-up"><LexAvatar size={40} /><p>Lexly está leyendo tu notificación con calma…</p><span>Identificando qué piden, el plazo y tus opciones</span></div>
      )}

      {analysis && (
        <div className="hac-result fade-up">
          {/* PLAZO destacado */}
          <div className="hac-plazo">
            <div className="hp-left">
              <div className="hp-label"><Icon name="hourglass" size={14} /> Plazo para responder</div>
              <div className="hp-text">{analysis.PLAZO_TEXTO || 'Consulta el plazo en la propia notificación'}</div>
              <div className="hp-warn">Los plazos con Hacienda son improrrogables. No esperes al último día.</div>
            </div>
            {dias != null && (
              <div className="hp-count"><div className="hp-num">{dias}</div><div className="hp-unit">{dias === 1 ? 'día' : 'días'} aprox.</div></div>
            )}
          </div>

          {/* Tipo + gravedad */}
          <div className="hac-type-row">
            {analysis.TIPO && <span className="hac-type"><Icon name="mail" size={13} /> {analysis.TIPO}</span>}
            {grav && <span className="hac-grav" style={{ color: grav.c, background: grav.bg }}>{grav.label}</span>}
            <button className="hac-new" onClick={reset}><Icon name="plus" size={14} /> Otra notificación</button>
          </div>

          {/* Derivación a profesional */}
          {grav && (analysis.GRAVEDAD || '').toLowerCase().includes('alta') && (
            <div className="hac-pro">
              <div className="hp-ic"><Icon name="warn" size={18} /></div>
              <div className="hp-body">
                <strong>Te recomendamos contar con un profesional</strong>
                <span>Por lo que vemos, esta comunicación puede tener consecuencias económicas o ser compleja. Antes de responder, conviene que un asesor fiscal o gestor colegiado revise tu caso.</span>
                {proRequested
                  ? <div className="hac-pro-ok"><Icon name="check" size={14} /> Hemos anotado tu solicitud. Te avisaremos cuando un profesional pueda revisarlo.</div>
                  : <button className="btn btn-ghost hac-pro-btn" onClick={() => setProRequested(true)}><Icon name="user" size={14} /> Quiero que un profesional revise esto</button>}
              </div>
            </div>
          )}

          <HacSection icon="mail" title="Qué te piden" content={analysis.PIDEN} />
          <HacSection icon="warn" title="Qué pasa si no respondes" content={analysis.CONSECUENCIAS} tone="red" />
          <HacSection icon="shield" title="Tus opciones" content={analysis.OPCIONES} />
          <HacSection icon="check" title="Pasos recomendados" content={analysis.PASOS} tone="violet" />

          {/* Preparar respuesta */}
          <div className="hac-draft-block">
            <div className="hac-draft-head">
              <div><strong>¿Quieres preparar tu respuesta?</strong><span>Lexly puede redactar un borrador de escrito que podrás revisar, editar y descargar.</span></div>
              {!draft && <button className="btn btn-primary" disabled={draftLoading} onClick={makeDraft}>{draftLoading ? <><Spinner /> Redactando…</> : <><Icon name="edit" size={15} /> Ayúdame a preparar la respuesta</>}</button>}
            </div>
            {draft && (
              <div className="hac-draft">
                <div className="hac-draft-bar">
                  <span><Icon name="file" size={14} /> Borrador de respuesta</span>
                  <div className="hdb-actions">
                    <button className="icon-btn" title="Copiar" onClick={() => navigator.clipboard?.writeText(draft)}><Icon name="copy" size={15} /></button>
                    <button className="btn btn-ghost hdb-dl" onClick={downloadDraft}><Icon name="download" size={14} /> Descargar</button>
                  </div>
                </div>
                <textarea className="hac-draft-text" value={draft} onChange={(e) => setDraft(e.target.value)} spellCheck={false} />
                <div className="hac-draft-warn"><Icon name="warn" size={13} /> Revisa este borrador con atención (y con un profesional si la situación es seria) antes de presentarlo ante la AEAT.</div>
              </div>
            )}
          </div>

          <p className="hac-foot-disc">Análisis orientativo. No sustituye el asesoramiento de un profesional colegiado. Verifica el plazo y los datos en la propia notificación y en la Sede electrónica de la AEAT.</p>
        </div>
      )}

      <style>{`
        .hac-disclaimer { display: flex; align-items: flex-start; gap: 11px; margin-top: 22px; padding: 14px 16px; background: var(--surface); border: 1px solid var(--violet-line); border-radius: 12px; font-size: 13px; color: var(--text-2); line-height: 1.5; }
        .hac-disclaimer .ic { color: var(--violet-soft); flex-shrink: 0; margin-top: 1px; }
        .hac-disclaimer b { color: var(--text); font-weight: 600; }

        .hac-input { margin-top: 22px; }
        .dropzone { border: 1.5px dashed var(--line-3); border-radius: var(--radius); background: var(--bg-2); padding: 28px; cursor: pointer; transition: border-color .15s, background .15s; min-height: 140px; display: flex; align-items: center; justify-content: center; }
        .dropzone.over { border-color: var(--violet); background: var(--violet-dim); }
        .dropzone.has-text { cursor: default; }
        .dz-center { text-align: center; display: flex; flex-direction: column; align-items: center; gap: 10px; }
        .dz-ic { width: 52px; height: 52px; border-radius: 14px; background: var(--surface-2); border: 1px solid var(--line); display: grid; place-items: center; color: var(--violet-soft); }
        .dz-title { font-size: 14px; color: var(--text); font-weight: 500; }
        .dz-title span { color: var(--violet-soft); }
        .dz-sub { font-size: 12px; color: var(--text-3); }
        .dz-file { display: flex; align-items: center; gap: 14px; width: 100%; }
        .dz-file-ic { width: 44px; height: 44px; border-radius: 11px; background: var(--violet-dim); border: 1px solid var(--violet-line); display: grid; place-items: center; color: var(--violet-soft); flex-shrink: 0; }
        .dz-file-meta { flex: 1; min-width: 0; }
        .dz-file-meta strong { display: block; font-size: 14px; color: var(--text); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .dz-file-meta span { font-size: 12px; color: var(--text-3); }
        .icon-btn { width: 32px; height: 32px; border-radius: 8px; display: grid; place-items: center; color: var(--text-3); border: 1px solid var(--line); transition: .15s; }
        .icon-btn:hover { color: var(--text); border-color: var(--line-2); background: var(--surface-2); }
        .rev-or { display: flex; align-items: center; gap: 14px; margin: 20px 0; color: var(--text-4); font-size: 12px; }
        .rev-or::before, .rev-or::after { content: ''; flex: 1; height: 1px; background: var(--line); }
        .hac-textarea { font-family: var(--serif); font-size: 14px; }
        .hac-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 16px; }

        .hac-loading { display: flex; flex-direction: column; align-items: center; text-align: center; gap: 11px; padding: 54px 20px; }
        .hac-loading p { font-size: 15px; color: var(--text); font-weight: 500; }
        .hac-loading span { font-size: 13px; color: var(--text-3); }

        .hac-result { margin-top: 24px; }
        .hac-plazo { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 20px 24px; border-radius: 16px; background: linear-gradient(135deg, rgba(251,191,36,0.14), rgba(251,191,36,0.04)); border: 1px solid rgba(251,191,36,0.34); }
        .hp-left { flex: 1; }
        .hp-label { display: inline-flex; align-items: center; gap: 7px; font-size: 11.5px; font-weight: 600; letter-spacing: 0.05em; text-transform: uppercase; color: var(--amber); margin-bottom: 8px; }
        .hp-text { font-size: 18px; font-weight: 600; color: var(--white); letter-spacing: -0.01em; line-height: 1.3; }
        .hp-warn { font-size: 12.5px; color: var(--text-2); margin-top: 7px; }
        .hp-count { text-align: center; flex-shrink: 0; line-height: 1; color: var(--amber); }
        .hp-num { font-size: 50px; font-weight: 700; letter-spacing: -0.04em; font-variant-numeric: tabular-nums; }
        .hp-unit { font-size: 12px; color: var(--text-3); margin-top: 4px; }

        .hac-type-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: 18px 0; }
        .hac-type { display: inline-flex; align-items: center; gap: 7px; font-size: 12.5px; font-weight: 600; color: var(--violet-soft); background: var(--violet-dim); border: 1px solid var(--violet-line); padding: 5px 12px; border-radius: 20px; }
        .hac-grav { font-size: 11.5px; font-weight: 600; padding: 5px 12px; border-radius: 20px; }
        .hac-new { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; font-weight: 500; color: var(--text-3); }
        .hac-new:hover { color: var(--text); }

        .hac-pro { display: flex; gap: 14px; align-items: flex-start; background: linear-gradient(180deg, var(--red-dim), transparent); border: 1px solid rgba(248,113,113,0.28); border-radius: 14px; padding: 16px 18px; margin-bottom: 18px; }
        .hac-pro .hp-ic { width: 38px; height: 38px; border-radius: 10px; background: rgba(248,113,113,0.14); display: grid; place-items: center; color: var(--red); flex-shrink: 0; }
        .hac-pro .hp-body strong { display: block; font-size: 14px; font-weight: 600; color: #ffb4b4; margin-bottom: 4px; }
        .hac-pro .hp-body > span { font-size: 13px; color: var(--text-2); line-height: 1.55; }
        .hac-pro-btn { margin-top: 12px; padding: 8px 14px; font-size: 12.5px; }
        .hac-pro-ok { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--green); margin-top: 12px; }

        .hac-draft-block { margin-top: 8px; padding: 18px 20px; background: var(--surface); border: 1px solid var(--line); border-radius: 14px; }
        .hac-draft-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
        .hac-draft-head strong { display: block; font-size: 14.5px; font-weight: 600; color: var(--white); }
        .hac-draft-head span { font-size: 12.5px; color: var(--text-3); }
        .hac-draft { margin-top: 16px; border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
        .hac-draft-bar { display: flex; align-items: center; justify-content: space-between; padding: 11px 14px; background: var(--bg-2); border-bottom: 1px solid var(--line); }
        .hac-draft-bar > span { display: inline-flex; align-items: center; gap: 8px; font-size: 12.5px; font-weight: 600; color: var(--text); }
        .hac-draft-bar .ic { color: var(--violet-soft); }
        .hdb-actions { display: flex; align-items: center; gap: 8px; }
        .hdb-dl { padding: 6px 11px; font-size: 12px; }
        .hac-draft-text { width: 100%; min-height: 320px; resize: vertical; border: none; outline: none; background: var(--bg-2); color: var(--text); font-family: var(--serif); font-size: 14px; line-height: 1.7; padding: 18px 20px; }
        .hac-draft-warn { display: flex; align-items: flex-start; gap: 8px; font-size: 11.5px; color: var(--amber); padding: 11px 14px; border-top: 1px solid var(--line); background: var(--amber-dim); line-height: 1.4; }
        .hac-draft-warn .ic { flex-shrink: 0; margin-top: 1px; }

        .hac-foot-disc { font-size: 11px; color: var(--text-4); margin-top: 22px; padding-top: 16px; border-top: 1px solid var(--line); line-height: 1.5; }

        @media (max-width: 700px) { .hac-plazo { flex-direction: column; align-items: flex-start; gap: 12px; } .hp-num { font-size: 40px; } }
      `}</style>
    </div>
  );
}

function HacSection({ icon, title, content, tone }) {
  if (!content) return null;
  const tc = tone === 'red' ? 'var(--red)' : tone === 'violet' ? 'var(--violet-soft)' : 'var(--text-2)';
  const tbg = tone === 'red' ? 'var(--red-dim)' : tone === 'violet' ? 'var(--violet-dim)' : 'var(--surface-2)';
  return (
    <div className="hac-sec card">
      <div className="hac-sec-head"><span className="hs-ic" style={{ color: tc, background: tbg }}><Icon name={icon} size={15} /></span> {title}</div>
      <div className="hac-sec-body"><Markdown text={content} /></div>
      <style>{`
        .hac-sec { padding: 16px 18px; margin-bottom: 12px; }
        .hac-sec-head { display: flex; align-items: center; gap: 10px; font-size: 14px; font-weight: 600; color: var(--white); margin-bottom: 10px; }
        .hs-ic { width: 30px; height: 30px; border-radius: 8px; display: grid; place-items: center; flex-shrink: 0; }
        .hac-sec-body { font-size: 13.5px; }
      `}</style>
    </div>
  );
}

Object.assign(window, { AsistenteHacienda });
