/* ============================================================
   INside One — Informe Semestral (Junta Directiva)
   Reporte ejecutivo de resultados con exportación PDF.
   ============================================================ */

const IS_DRAFT_KEY = "inside_informe_semestral_v1";

function isPeriodInRange(dateStr, period) {
  if (!dateStr) return false;
  const d   = new Date(dateStr);
  const yr  = d.getFullYear();
  const mo  = d.getMonth(); // 0-based
  const [pType, pYear] = period.split("-");
  const y = parseInt(pYear);
  if (yr !== y) return false;
  if (pType === "H1") return mo <= 5;
  if (pType === "H2") return mo >= 6;
  if (pType === "Q1") return mo <= 2;
  if (pType === "Q2") return mo >= 3 && mo <= 5;
  if (pType === "Q3") return mo >= 6 && mo <= 8;
  if (pType === "Q4") return mo >= 9;
  return true;
}

function generatePeriods() {
  const now = new Date();
  const yr  = now.getFullYear();
  const periods = [];
  for (let y = yr; y >= yr-1; y--) {
    periods.push(`H2-${y}`, `H1-${y}`, `Q4-${y}`, `Q3-${y}`, `Q2-${y}`, `Q1-${y}`);
  }
  return periods;
}

function periodLabel(p) {
  const [t, y] = p.split("-");
  const map = { H1:"Primer semestre", H2:"Segundo semestre", Q1:"Q1", Q2:"Q2", Q3:"Q3", Q4:"Q4" };
  return `${map[t]||t} ${y}`;
}

function fmtISMoney(n) {
  if (n >= 1000000) return "$" + (n/1000000).toFixed(2) + "M";
  if (n >= 1000)    return "$" + (n/1000).toFixed(1) + "k";
  return window.fmtMoney(n);
}

function Section({ title, children }) {
  return (
    <div style={{ marginBottom:24 }}>
      <div style={{ fontSize:11, fontWeight:700, textTransform:"uppercase", letterSpacing:".1em",
        color:"var(--muted)", marginBottom:12, paddingBottom:8, borderBottom:"1px solid var(--border)" }}>
        {title}
      </div>
      {children}
    </div>
  );
}

function EditableField({ label, value, onChange, multiline, placeholder }) {
  return (
    <label style={{ display:"block", marginBottom:14 }}>
      <div style={{ fontSize:12, fontWeight:600, color:"var(--muted)", marginBottom:5 }}>{label}</div>
      {multiline ? (
        <textarea className="inp" rows={4} value={value} onChange={e=>onChange(e.target.value)}
          style={{ resize:"vertical", fontFamily:"inherit", lineHeight:1.6 }} placeholder={placeholder} />
      ) : (
        <input className="inp" value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} />
      )}
    </label>
  );
}

function MetaKpi({ label, value, sub }) {
  return (
    <div style={{ textAlign:"center", padding:"14px 10px" }}>
      <div style={{ fontSize:22, fontWeight:800, color:"var(--text)" }}>{value}</div>
      <div style={{ fontSize:11, fontWeight:600, color:"var(--muted)", marginTop:2 }}>{label}</div>
      {sub && <div style={{ fontSize:11, color:"var(--muted)", marginTop:2 }}>{sub}</div>}
    </div>
  );
}

// ── InformeSemestralView ──────────────────────────────────────
function InformeSemestralView() {
  const { quotes, opps = [], settings } = React.useContext(window.AppCtx);
  const periods = React.useMemo(generatePeriods, []);
  const [period, setPeriod] = React.useState(periods[0]);
  const [preview, setPreview] = React.useState(false);

  // Draft state
  const [draft, setDraftState] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(IS_DRAFT_KEY)||"{}"); } catch { return {}; }
  });
  const setDraft = (patch) => setDraftState(d => {
    const next = { ...d, ...patch };
    localStorage.setItem(IS_DRAFT_KEY, JSON.stringify(next));
    return next;
  });
  const f = (k, def="") => draft[k] ?? def;

  // Computed stats from the selected period
  const stats = React.useMemo(() => {
    const pq = quotes.filter(q => isPeriodInRange(q.date, period));
    const accepted = pq.filter(q=>q.status==="accepted");
    const rejected = pq.filter(q=>q.status==="rejected");
    const sent     = pq.filter(q=>q.status==="sent");
    const closed   = accepted.length + rejected.length;
    const winRate  = closed>0 ? Math.round(accepted.length/closed*100) : 0;
    const totalQuoted = pq.reduce((s,q)=>s+(q.total||0),0);
    const totalWon    = accepted.reduce((s,q)=>s+(q.total||0),0);
    const avgMargin   = pq.length>0 ? pq.reduce((s,q)=>s+(q.margin_pct||0),0)/pq.length : 0;

    const pipeOps = opps.filter(o => {
      if (!o.created_at) return false;
      return isPeriodInRange(new Date(o.created_at).toISOString().slice(0,10), period);
    });
    const pipeVal = pipeOps.filter(o=>o.stage!=="adjudicado"&&o.stage!=="no_adjudicado")
      .reduce((s,o)=>s+(o.value||0),0);
    const wonPipe = pipeOps.filter(o=>o.stage==="adjudicado").reduce((s,o)=>s+(o.value||0),0);

    // Top clients
    const clientMap = {};
    pq.forEach(q => {
      const k = q.client_company||q.client_name||"—";
      if (!clientMap[k]) clientMap[k]={ name:k,total:0,won:0 };
      clientMap[k].total += q.total||0;
      if (q.status==="accepted") clientMap[k].won += q.total||0;
    });
    const topClients = Object.values(clientMap).sort((a,b)=>b.total-a.total).slice(0,5);

    return { pq, accepted, rejected, sent, closed, winRate, totalQuoted, totalWon, avgMargin, pipeVal, wonPipe, topClients };
  }, [quotes, opps, period]);

  const handlePrint = () => {
    window.print();
  };

  if (preview) {
    // PDF preview mode
    return (
      <div style={{ padding:"20px 20px 60px" }}>
        <div style={{ display:"flex", alignItems:"center", gap:12, marginBottom:24 }}>
          <window.Btn variant="outline" size="sm" icon="chevron" onClick={() => setPreview(false)}>
            Volver
          </window.Btn>
          <window.Btn variant="primary" size="sm" icon="download" onClick={handlePrint}>
            Exportar PDF
          </window.Btn>
          <span style={{ fontSize:13, color:"var(--muted)" }}>Informe listo para exportar</span>
        </div>

        <div id="informe-semestral-print" style={{ maxWidth:760, margin:"0 auto",
          background:"var(--surface)", border:"1px solid var(--border)", borderRadius:12,
          padding:"48px 52px", fontFamily:"var(--body)" }}>

          {/* Header */}
          <div style={{ borderBottom:"3px solid var(--text)", paddingBottom:20, marginBottom:32 }}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:20 }}>
              <div>
                <div style={{ fontSize:10, fontWeight:700, letterSpacing:".2em", textTransform:"uppercase", color:"var(--muted)", marginBottom:8 }}>
                  {settings.company_name}
                </div>
                <div style={{ fontSize:26, fontWeight:800, lineHeight:1.2, marginBottom:6 }}>
                  Informe de Resultados<br />{periodLabel(period)}
                </div>
                <div style={{ fontSize:13, color:"var(--muted)" }}>
                  Presentado a: {f("dirigido_a","Junta Directiva")}
                </div>
              </div>
              <div style={{ textAlign:"right", flexShrink:0 }}>
                <div style={{ fontSize:12, color:"var(--muted)" }}>Elaborado por</div>
                <div style={{ fontWeight:600, fontSize:14 }}>{f("elaborado_por")}</div>
                <div style={{ fontSize:12, color:"var(--muted)", marginTop:4 }}>
                  {f("fecha_presentacion", new Date().toLocaleDateString("es-PA",{day:"2-digit",month:"long",year:"numeric"}))}
                </div>
              </div>
            </div>
          </div>

          {/* KPI grid */}
          <div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:0,
            border:"1px solid var(--border)", borderRadius:10, overflow:"hidden", marginBottom:32 }}>
            {[
              { label:"Total cotizado",  value: fmtISMoney(stats.totalQuoted) },
              { label:"Adjudicado",      value: fmtISMoney(stats.totalWon) },
              { label:"Tasa de cierre",  value: stats.winRate+"%" },
              { label:"Margen promedio", value: stats.avgMargin.toFixed(1)+"%" },
            ].map((k,i) => (
              <div key={i} style={{ padding:"16px 12px", borderRight: i<3?"1px solid var(--border)":"none",
                textAlign:"center" }}>
                <div style={{ fontSize:20, fontWeight:800 }}>{k.value}</div>
                <div style={{ fontSize:10, color:"var(--muted)", textTransform:"uppercase", letterSpacing:".06em", marginTop:4 }}>{k.label}</div>
              </div>
            ))}
          </div>

          {/* Resumen ejecutivo */}
          {f("resumen") && (
            <div style={{ marginBottom:28 }}>
              <div style={{ fontSize:13, fontWeight:700, textTransform:"uppercase", letterSpacing:".08em", marginBottom:10 }}>
                Resumen Ejecutivo
              </div>
              <div style={{ fontSize:13, lineHeight:1.7, color:"var(--text)", whiteSpace:"pre-wrap" }}>
                {f("resumen")}
              </div>
            </div>
          )}

          {/* Resultados de ventas */}
          <div style={{ marginBottom:28 }}>
            <div style={{ fontSize:13, fontWeight:700, textTransform:"uppercase", letterSpacing:".08em", marginBottom:10 }}>
              Resultados de Ventas
            </div>
            <table style={{ width:"100%", borderCollapse:"collapse", fontSize:12 }}>
              <thead>
                <tr style={{ background:"var(--bg2)" }}>
                  {["Métrica","Resultado","Detalle"].map(h => (
                    <th key={h} style={{ padding:"8px 12px", textAlign:"left", fontWeight:600, borderBottom:"1px solid var(--border)" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {[
                  ["Cotizaciones emitidas", stats.pq.length+" cotizaciones", `Total: ${fmtISMoney(stats.totalQuoted)}`],
                  ["Proyectos adjudicados", stats.accepted.length+" proyectos", `Valor: ${fmtISMoney(stats.totalWon)}`],
                  ["Proyectos no adjudicados", stats.rejected.length+" proyectos", ""],
                  ["Cotizaciones en negociación", stats.sent.length+" cotizaciones", `En riesgo: ${fmtISMoney(stats.sent.reduce((s,q)=>s+(q.total||0),0))}`],
                  ["Tasa de cierre", stats.winRate+"%", `Sobre ${stats.closed} procesos cerrados`],
                  ["Margen promedio", stats.avgMargin.toFixed(1)+"%", "Promedio ponderado"],
                ].map(([m,r,d],i) => (
                  <tr key={i} style={{ borderBottom:"1px solid var(--border)" }}>
                    <td style={{ padding:"8px 12px", color:"var(--muted)" }}>{m}</td>
                    <td style={{ padding:"8px 12px", fontWeight:600 }}>{r}</td>
                    <td style={{ padding:"8px 12px", color:"var(--muted)" }}>{d}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Top clients */}
          {stats.topClients.length > 0 && (
            <div style={{ marginBottom:28 }}>
              <div style={{ fontSize:13, fontWeight:700, textTransform:"uppercase", letterSpacing:".08em", marginBottom:10 }}>
                Principales Clientes del Período
              </div>
              <table style={{ width:"100%", borderCollapse:"collapse", fontSize:12 }}>
                <thead>
                  <tr style={{ background:"var(--bg2)" }}>
                    {["Cliente","Total cotizado","Adjudicado"].map(h => (
                      <th key={h} style={{ padding:"8px 12px", textAlign:"left", fontWeight:600, borderBottom:"1px solid var(--border)" }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {stats.topClients.map((c,i) => (
                    <tr key={i} style={{ borderBottom:"1px solid var(--border)" }}>
                      <td style={{ padding:"8px 12px" }}>{c.name}</td>
                      <td style={{ padding:"8px 12px", fontFamily:"var(--mono)", fontWeight:600 }}>{fmtISMoney(c.total)}</td>
                      <td style={{ padding:"8px 12px", fontFamily:"var(--mono)", color: c.won>0?"#22c55e":"var(--muted)" }}>
                        {c.won>0?fmtISMoney(c.won):"—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* Narrative sections */}
          {[
            ["logros",       "Principales Logros"],
            ["retos",        "Retos y Desafíos"],
            ["oportunidades","Oportunidades Identificadas"],
            ["plan",         "Plan de Acción Siguiente Período"],
          ].map(([k,title]) => f(k) && (
            <div key={k} style={{ marginBottom:24 }}>
              <div style={{ fontSize:13, fontWeight:700, textTransform:"uppercase", letterSpacing:".08em", marginBottom:8 }}>
                {title}
              </div>
              <div style={{ fontSize:13, lineHeight:1.7, whiteSpace:"pre-wrap" }}>{f(k)}</div>
            </div>
          ))}

          {/* Footer */}
          <div style={{ marginTop:40, paddingTop:16, borderTop:"1px solid var(--border)",
            fontSize:11, color:"var(--muted)", display:"flex", justifyContent:"space-between" }}>
            <span>{settings.company_name}</span>
            <span>Documento confidencial — {periodLabel(period)}</span>
          </div>
        </div>
      </div>
    );
  }

  // Edit mode
  return (
    <div style={{ padding:"28px 28px 80px" }}>
      <div style={{ display:"flex", alignItems:"flex-start", justifyContent:"space-between", marginBottom:24, gap:16, flexWrap:"wrap" }}>
        <div>
          <h1 style={{ margin:0, fontSize:22, fontWeight:800 }}>Informe Semestral</h1>
          <div style={{ fontSize:13, color:"var(--muted)", marginTop:4 }}>Reporte ejecutivo para la junta directiva</div>
        </div>
        <div style={{ display:"flex", gap:8 }}>
          <select className="inp" style={{ width:"auto" }} value={period} onChange={e => setPeriod(e.target.value)}>
            {periods.map(p => <option key={p} value={p}>{periodLabel(p)}</option>)}
          </select>
          <window.Btn variant="primary" size="sm" icon="doc" onClick={() => setPreview(true)}>
            Vista previa / PDF
          </window.Btn>
        </div>
      </div>

      {/* Auto-computed stats preview */}
      <div style={{ background:"var(--surface)", border:"1px solid var(--border)", borderRadius:13, marginBottom:24, overflow:"hidden" }}>
        <div style={{ padding:"14px 20px", borderBottom:"1px solid var(--border)", background:"var(--bg2)",
          fontSize:13, fontWeight:700 }}>
          Métricas automáticas — {periodLabel(period)}
        </div>
        <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit,minmax(140px,1fr))", borderBottom:"none" }}>
          {[
            { label:"Cotizaciones", value: stats.pq.length },
            { label:"Total cotizado", value: fmtISMoney(stats.totalQuoted) },
            { label:"Adjudicado", value: fmtISMoney(stats.totalWon) },
            { label:"Tasa cierre", value: stats.winRate+"%" },
            { label:"Margen prom.", value: stats.avgMargin.toFixed(1)+"%" },
            { label:"Pipeline", value: fmtISMoney(stats.pipeVal) },
          ].map((k,i,arr) => (
            <div key={i} style={{ padding:"16px 20px", borderRight: i<arr.length-1?"1px solid var(--border)":"none",
              borderBottom:"none" }}>
              <div style={{ fontSize:20, fontWeight:800 }}>{k.value}</div>
              <div style={{ fontSize:11, color:"var(--muted)", textTransform:"uppercase", letterSpacing:".06em", marginTop:4 }}>
                {k.label}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Editable sections */}
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:20 }}>
        <div style={{ background:"var(--surface)", border:"1px solid var(--border)", borderRadius:13, padding:"20px 22px" }}>
          <Section title="Información del informe">
            <EditableField label="Dirigido a" value={f("dirigido_a","Junta Directiva")}
              onChange={v=>setDraft({dirigido_a:v})} placeholder="Junta Directiva" />
            <EditableField label="Elaborado por" value={f("elaborado_por")}
              onChange={v=>setDraft({elaborado_por:v})} placeholder="Nombre del responsable" />
            <EditableField label="Fecha de presentación" value={f("fecha_presentacion")}
              onChange={v=>setDraft({fecha_presentacion:v})} placeholder="DD de mes de YYYY" />
          </Section>

          <Section title="Resumen ejecutivo">
            <EditableField multiline value={f("resumen")} onChange={v=>setDraft({resumen:v})}
              label="" placeholder="Síntesis de los resultados del período, contexto del mercado, decisiones clave tomadas..." />
          </Section>

          <Section title="Principales logros">
            <EditableField multiline value={f("logros")} onChange={v=>setDraft({logros:v})}
              label="" placeholder="• Proyectos cerrados más relevantes&#10;• Nuevos clientes ganados&#10;• Metas alcanzadas..." />
          </Section>
        </div>

        <div style={{ background:"var(--surface)", border:"1px solid var(--border)", borderRadius:13, padding:"20px 22px" }}>
          <Section title="Retos y desafíos">
            <EditableField multiline value={f("retos")} onChange={v=>setDraft({retos:v})}
              label="" placeholder="• Obstáculos encontrados&#10;• Proyectos perdidos y razones&#10;• Factores externos que afectaron..." />
          </Section>

          <Section title="Oportunidades identificadas">
            <EditableField multiline value={f("oportunidades")} onChange={v=>setDraft({oportunidades:v})}
              label="" placeholder="• Clientes con potencial de cierre&#10;• Nuevos mercados o segmentos&#10;• Proyectos en conversación..." />
          </Section>

          <Section title="Plan de acción — próximo período">
            <EditableField multiline value={f("plan")} onChange={v=>setDraft({plan:v})}
              label="" placeholder="• Metas de ventas&#10;• Estrategias a implementar&#10;• Acciones de seguimiento prioritarias..." />
          </Section>
        </div>
      </div>

      <div style={{ fontSize:12, color:"var(--muted)", marginTop:16, textAlign:"center" }}>
        Los cambios se guardan automáticamente en este navegador. Usa "Vista previa / PDF" para generar el documento.
      </div>
    </div>
  );
}

window.InformeSemestralView = InformeSemestralView;
