/* global React */
/* report-generator.jsx
   Phase 04: Justified price report generator.
   Calls the Anthropic API to draft the full report narrative,
   then POSTs to /generate-report (local Node server) to produce the .docx.
   Falls back to a clipboard-copy of the markdown draft if the server isn't running.
*/

const { useState: useRptState, useRef: useRptRef } = React;

const RPT_STRINGS = {
  en: {
    eyebrow: '04 · Report',
    title: 'Generate price justification report',
    sub: 'AI drafts a justified offer document you can edit before presenting to the client.',
    generateBtn: 'Generate Word report',
    generating: 'Drafting report…',
    downloadBtn: '⬇ Download .docx',
    copyBtn: 'Copy draft text',
    copied: 'Copied ✓',
    previewLabel: 'Draft preview — edit before downloading',
    errorMsg: 'Could not generate report. Check console for details.',
    sectionCover: 'Cover & executive summary',
    sectionCost: 'Cost justification',
    sectionRoi: 'ROI analysis',
    sectionPrice: 'Pricing decision',
    sectionNext: 'Next steps',
  },
  es: {
    eyebrow: '04 · Reporte',
    title: 'Generar reporte de justificación de precio',
    sub: 'La IA redacta un documento de oferta justificada que puedes editar antes de presentar al cliente.',
    generateBtn: 'Generar reporte Word',
    generating: 'Redactando reporte…',
    downloadBtn: '⬇ Descargar .docx',
    copyBtn: 'Copiar borrador',
    copied: 'Copiado ✓',
    previewLabel: 'Vista previa del borrador — edita antes de descargar',
    errorMsg: 'No se pudo generar el reporte. Revisa la consola.',
    sectionCover: 'Portada y resumen ejecutivo',
    sectionCost: 'Justificación de costo',
    sectionRoi: 'Análisis de ROI',
    sectionPrice: 'Decisión de precio',
    sectionNext: 'Próximos pasos',
  },
};

// ── Build the report-drafting prompt ─────────────────────────────────────
function buildReportPrompt(ctx, lang) {
  const isES = lang === 'es';
  const fmt = (n) => new Intl.NumberFormat('en-US', { style: 'currency', currency: ctx.currency || 'USD', maximumFractionDigits: 0 }).format(n);

  const headers = isES
    ? ['RESUMEN EJECUTIVO', 'JUSTIFICACIÓN DE COSTO', 'ANÁLISIS DE ROI', 'DECISIÓN DE PRECIO', 'PRÓXIMOS PASOS']
    : ['EXECUTIVE SUMMARY', 'COST JUSTIFICATION', 'ROI ANALYSIS', 'PRICING DECISION', 'NEXT STEPS'];

  if (isES) {
    return {
      system: `Eres consultor senior en DiALOGA, una empresa de soluciones de IA. Redacta un documento profesional, persuasivo y orientado al cliente para justificar el precio. IMPORTANTE: escribe TODO el documento en español, incluyendo los encabezados de sección.

Tono: seguro, claro, consultivo. Sin jerga. Sin frases de relleno.
Formato: usa exactamente los encabezados de sección proporcionados. Bajo cada encabezado, escribe 2–4 párrafos cortos. Sé específico con las cifras — cita el costo y el ROI directamente.
Salida: solo texto plano. Sin markdown, sin viñetas, sin asteriscos. Usa líneas en blanco para separar párrafos.`,

      user: `Redacta un reporte de justificación de precio para el siguiente proyecto. Usa exactamente estos encabezados de sección (textualmente, en mayúsculas):

${headers.join('\n')}

Datos del proyecto:
- Cliente / Proyecto: ${ctx.deal || '(sin nombre)'}
- Costo operativo DiALOGA: ${fmt(ctx.cost)}
- ROI esperado del cliente (1er año): ${fmt(ctx.roi)}
- Precio recomendado: ${fmt(ctx.finalPrice)}
- Rango de precio: ${fmt(ctx.bandMin)} – ${fmt(ctx.bandMax)}
- Margen al precio recomendado: ${(ctx.margin * 100).toFixed(1)}%
- % del ROI del cliente capturado: ${(ctx.captured * 100).toFixed(1)}%
- Desglose de costo: ${ctx.costBreakdown || 'No proporcionado'}
- Desglose de ROI: ${ctx.roiBreakdown || 'No proporcionado'}
- Notas: ${ctx.notes || 'Ninguna'}
- Fecha: ${new Date().toLocaleDateString('es-ES', { year: 'numeric', month: 'long', day: 'numeric' })}

Redacta el reporte completo ahora, todo en español.`
    };
  }

  return {
    system: `You are a senior consultant at DiALOGA, an AI solutions company. Write a professional, persuasive, client-facing price justification document in English.

Tone: confident, clear, consultative. No jargon. No filler phrases like "In conclusion" or "It is worth noting."
Format: Use the exact section headers provided. Under each header, write 2–4 short paragraphs. Be specific with numbers — cite the cost and ROI figures directly.
Output: plain text only. No markdown, no bullet symbols, no asterisks. Use blank lines to separate paragraphs.`,

    user: `Write a price justification report for the following deal. Use exactly these section headers (verbatim):

${headers.join('\n')}

Deal data:
- Client / Project: ${ctx.deal || '(unnamed)'}
- DiALOGA operative cost: ${fmt(ctx.cost)}
- Client's expected 1st-year ROI: ${fmt(ctx.roi)}
- Recommended price: ${fmt(ctx.finalPrice)}
- Price range: ${fmt(ctx.bandMin)} – ${fmt(ctx.bandMax)}
- Margin at recommended price: ${(ctx.margin * 100).toFixed(1)}%
- % of client ROI captured: ${(ctx.captured * 100).toFixed(1)}%
- Cost breakdown: ${ctx.costBreakdown || 'Not provided'}
- ROI breakdown: ${ctx.roiBreakdown || 'Not provided'}
- Notes: ${ctx.notes || 'None'}
- Date: ${new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}

Write the full report now.`
  };
}

// ── Parse plain-text report into sections ────────────────────────────────
function parseSections(text, lang) {
  const headers = lang === 'es'
    ? ['RESUMEN EJECUTIVO', 'JUSTIFICACIÓN DE COSTO', 'ANÁLISIS DE ROI', 'DECISIÓN DE PRECIO', 'PRÓXIMOS PASOS']
    : ['EXECUTIVE SUMMARY', 'COST JUSTIFICATION', 'ROI ANALYSIS', 'PRICING DECISION', 'NEXT STEPS'];
  const sections = [];
  for (let i = 0; i < headers.length; i++) {
    const h = headers[i];
    const start = text.indexOf(h);
    if (start === -1) continue;
    const nextHeader = headers.slice(i + 1).map(nh => text.indexOf(nh)).filter(p => p > start);
    const end = nextHeader.length ? Math.min(...nextHeader) : text.length;
    const body = text.slice(start + h.length, end).trim();
    sections.push({ header: h, body });
  }
  return sections;
}

// ── Generate .docx via fetch to local Node server ─────────────────────────
async function requestDocx(reportData) {
  const response = await fetch('/api/generate-report', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(reportData),
  });
  if (!response.ok) throw new Error(`Server error ${response.status}`);
  const blob = await response.blob();
  return blob;
}

// ── Download helper ───────────────────────────────────────────────────────
function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

// ── EditableSection ───────────────────────────────────────────────────────
function EditableSection({ header, body, onChange }) {
  return (
    <div className="rpt-section">
      <div className="rpt-section-header">{header}</div>
      <textarea
        className="rpt-section-body"
        value={body}
        onChange={e => onChange(e.target.value)}
        rows={Math.max(4, body.split('\n').length + 2)}
      />
    </div>
  );
}

// ── Main component ────────────────────────────────────────────────────────
window.ReportGenerator = function ReportGenerator({ lang, ctx }) {
  const t = RPT_STRINGS[lang] || RPT_STRINGS.en;
  const [phase, setPhase] = useRptState('idle'); // idle | generating | editing | downloading
  const [sections, setSections] = useRptState([]);
  const [rawText, setRawText] = useRptState('');
  const [error, setError] = useRptState('');
  const [copied, setCopied] = useRptState(false);
  const [serverAvailable, setServerAvailable] = useRptState(null); // null=unknown, true, false

  // On Vercel the API functions are always available (same origin).
  const checkServer = async () => {
    setServerAvailable(true);
    return true;
  };

  const generate = async () => {
    setPhase('generating');
    setError('');
    try {
      const { system, user } = buildReportPrompt(ctx, lang);
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: [{ role: 'user', content: `${system}\n\n---\n\n${user}` }],
          modelSelection: 'advanced',
        }),
      });
      const data = await response.json();
      const text = data?.response || '';
      if (!text) throw new Error('Empty response');
      const parsed = parseSections(text, lang);
      setSections(parsed.length ? parsed : [{ header: 'DRAFT', body: text }]);
      setRawText(text);
      const hasServer = await checkServer();
      setPhase('editing');
    } catch (e) {
      setError(t.errorMsg);
      setPhase('idle');
    }
  };

  const downloadDocx = async () => {
    setPhase('downloading');
    const fullText = sections.map(s => `${s.header}\n\n${s.body}`).join('\n\n');
    const reportData = {
      deal: ctx.deal,
      date: new Date().toLocaleDateString(lang === 'es' ? 'es-ES' : 'en-US', { year: 'numeric', month: 'long', day: 'numeric' }),
      cost: ctx.cost,
      roi: ctx.roi,
      finalPrice: ctx.finalPrice,
      bandMin: ctx.bandMin,
      bandMax: ctx.bandMax,
      margin: ctx.margin,
      captured: ctx.captured,
      currency: ctx.currency || 'USD',
      sections,
      lang,
    };
    try {
      const blob = await requestDocx(reportData);
      const safeName = (ctx.deal || 'dialoga-report').replace(/[^a-zA-Z0-9]/g, '-').toLowerCase();
      downloadBlob(blob, `${safeName}-price-report.docx`);
      setPhase('editing');
    } catch {
      // Server not available — copy text to clipboard as fallback
      try {
        await navigator.clipboard.writeText(fullText);
        setCopied(true);
        setTimeout(() => setCopied(false), 2500);
      } catch {}
      setPhase('editing');
    }
  };

  const copyText = async () => {
    const fullText = sections.map(s => `${s.header}\n\n${s.body}`).join('\n\n');
    try {
      await navigator.clipboard.writeText(fullText);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {}
  };

  const updateSection = (i, body) => {
    setSections(prev => prev.map((s, idx) => idx === i ? { ...s, body } : s));
  };

  return (
    <section className="rpt-section-wrap">
      <div className="rpt-header">
        <div>
          <div className="est-phase-eyebrow">{t.eyebrow}</div>
          <h2 className="est-phase-title">{t.title}</h2>
          <p className="est-phase-sub">{t.sub}</p>
        </div>
      </div>

      {phase === 'idle' && (
        <div className="rpt-idle">
          <button className="est-btn-primary" onClick={generate}>{t.generateBtn}</button>
          {error && <div className="rpt-error">{error}</div>}
        </div>
      )}

      {phase === 'generating' && (
        <div className="rpt-generating">
          <div className="est-thinking" style={{ display: 'inline-flex', gap: '6px', padding: '16px 0' }}>
            <span className="est-dot" /><span className="est-dot" /><span className="est-dot" />
          </div>
          <span className="rpt-generating-label">{t.generating}</span>
        </div>
      )}

      {(phase === 'editing' || phase === 'downloading') && sections.length > 0 && (
        <div className="rpt-editor">
          <div className="rpt-editor-toolbar">
            <span className="rpt-preview-label">{t.previewLabel}</span>
            <div className="rpt-toolbar-actions">
              <button className="est-btn-ghost small" onClick={copyText}>
                {copied ? t.copied : t.copyBtn}
              </button>
              {serverAvailable !== false && (
                <button
                  className="est-btn-primary"
                  onClick={downloadDocx}
                  disabled={phase === 'downloading'}
                >
                  {phase === 'downloading' ? t.generating : t.downloadBtn}
                </button>
              )}
              {serverAvailable === false && (
                <button className="est-btn-primary" onClick={copyText}>
                  {copied ? t.copied : t.copyBtn}
                </button>
              )}
            </div>
          </div>
          {sections.map((s, i) => (
            <EditableSection
              key={i}
              header={s.header}
              body={s.body}
              onChange={body => updateSection(i, body)}
            />
          ))}
          <div className="rpt-editor-bottom">
            <button className="est-btn-ghost" onClick={() => setPhase('idle')}>
              {lang === 'es' ? 'Regenerar reporte' : 'Regenerate report'}
            </button>
            {serverAvailable !== false && (
              <button
                className="est-btn-primary"
                onClick={downloadDocx}
                disabled={phase === 'downloading'}
              >
                {phase === 'downloading' ? t.generating : t.downloadBtn}
              </button>
            )}
          </div>
        </div>
      )}
    </section>
  );
};
