/* ANISAN — Histórico & Inteligência de Negócio.
   Indicadores: Faturamento, Atendimentos, Delivery %, Ticket médio e % vertical
   do Resultado operacional. Cada um, por mês e por ano, segue a regra:
   override manual do usuário onde preenchido; senão o valor do SISTEMA (derivado
   do livro de receitas / DRE). Séries históricas multi-ano para ver tendências.
   "Editar dados manuais" preenche qualquer ano; vazio volta ao sistema. */

const HIST_DEF = {
  fat:      { label: "Faturamento", fmt: (v) => window.BRLk(v), fmtFull: (v) => window.BRL(v), color: "var(--brass)", money: true },
  atend:    { label: "Atendimentos", fmt: (v) => Math.round(v).toLocaleString("pt-BR"), fmtFull: (v) => Math.round(v).toLocaleString("pt-BR"), color: "var(--slate)" },
  delivery: { label: "Delivery %", fmt: (v) => (Math.round(v * 10) / 10) + "%", fmtFull: (v) => (Math.round(v * 10) / 10) + "%", color: "var(--jade)", pct: true },
  ticket:   { label: "Ticket médio", fmt: (v) => window.BRL(v), fmtFull: (v) => window.BRL(v), color: "var(--clay)", money: true },
  vert:     { label: "Result. operac. (% receita)", fmt: (v) => (Math.round(v * 10) / 10) + "%", fmtFull: (v) => (Math.round(v * 10) / 10) + "%", color: "var(--sand)", pct: true },
};

function Historico({ unit }) {
  const store = window.useStore();
  const data = store.data;
  const D = window.ANISAN_DATA;
  const cons = window.isCons(unit);
  const mobile = window.useIsMobile();

  const anos = [window.YEAR - 2, window.YEAR - 1, window.YEAR];
  const [ano, setAno] = React.useState(window.YEAR);
  const [ind, setInd] = React.useState("fat");
  const [editar, setEditar] = React.useState(false);
  const [editU, setEditU] = React.useState(cons ? D.units[0] : unit);

  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const Button = window.Button, MoneyInput = window.MoneyInput, Input = window.Input;
  const def = HIST_DEF[ind];

  // série efetiva do ano selecionado (todos indicadores) p/ a unidade atual
  const serie = window.histSerie(data, ano, unit);
  const mesAtualIdx = (ano === window.YEAR) ? (parseInt((window.todayISO()).slice(5, 7), 10) - 1) : 11;

  // KPIs (valor do mês atual / último do ano) com Δ vs ano anterior
  const seriePrev = window.histSerie(data, ano - 1, unit);
  const kpiVal = (s, k) => k === "delivery" || k === "vert" || k === "ticket"
    ? (s[k][mesAtualIdx] || 0)
    : s[k].slice(0, mesAtualIdx + 1).reduce((a, b) => a + b, 0); // fat/atend: acumulado no ano até o mês
  const kpis = window.HIST_INDS.map((k) => {
    const cur = kpiVal(serie, k), prev = kpiVal(seriePrev, k);
    const delta = prev ? ((cur - prev) / prev) * 100 : null;
    const dd = HIST_DEF[k];
    return { k, label: dd.label, value: dd.fmtFull(cur), delta, auto: (k === "fat" && ano === window.YEAR) || (k === "vert" && ano === window.YEAR), derived: k === "ticket" };
  });

  // séries históricas: uma linha por ano para o indicador selecionado
  const lineSeries = anos.map((y, i) => ({
    name: String(y) + (y === window.YEAR ? " (atual)" : ""),
    values: window.histSerie(data, y, unit)[ind],
    color: y === window.YEAR ? def.color : (y === window.YEAR - 1 ? "var(--muted)" : "var(--hairline-strong)"),
    dashed: y !== window.YEAR,
  }));

  // ranking real (faturamento recebido no ano de trabalho por unidade)
  const ranking = D.units.map(n => ({ n, v: window.fatAnoReal(data, n), c: D.accents[n] })).sort((a, b) => b.v - a.v);
  const rankMax = Math.max(1, ...ranking.map(r => r.v));

  // edição: grava data.histManual[ano][editU][ind][mes]
  const setManual = (indi, i, raw) => store.set(d => {
    d.histManual = d.histManual || {};
    d.histManual[String(ano)] = d.histManual[String(ano)] || {};
    d.histManual[String(ano)][editU] = d.histManual[String(ano)][editU] || {};
    const o = d.histManual[String(ano)][editU];
    o[indi] = (o[indi] || []).slice(0, 12); while (o[indi].length < 12) o[indi].push(0);
    o[indi][i] = window.parseBRL(raw);
  }, "histManual");
  const sysU = (indi) => window.histSys(data, ano, editU, indi);
  const ovU = (indi) => window.histOv(data, ano, editU, indi);

  const editInds = ["fat", "atend", "delivery", "ticket", "vert"];

  return (
    <div style={{ padding: mobile ? "18px 14px 40px" : "26px 32px 48px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 14, marginBottom: 20 }}>
        <SectionTitle style={{ margin: 0 }}>Histórico & inteligência de negócio</SectionTitle>
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-pill)", padding: "5px 6px" }}>
            <button onClick={() => setAno(a => Math.max(anos[0], a - 1))} style={navMiniH}><i data-lucide="chevron-left" style={{ width: 16, height: 16, strokeWidth: 1.8 }}></i></button>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.04em", color: "var(--paper)", minWidth: 56, textAlign: "center" }}>{ano}{ano === window.YEAR ? " ·" : ""}</span>
            <button onClick={() => setAno(a => Math.min(anos[anos.length - 1], a + 1))} style={navMiniH}><i data-lucide="chevron-right" style={{ width: 16, height: 16, strokeWidth: 1.8 }}></i></button>
          </div>
          <Button size="sm" variant={editar ? "primary" : "default"} onClick={() => setEditar(v => !v)}>{editar ? "Concluir edição" : "Editar dados manuais"}</Button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12, marginBottom: 22 }}>
        {kpis.map((k) => (
          <div key={k.k} style={{ background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-tile)", padding: "14px 16px", cursor: "pointer", outline: ind === k.k ? "1.5px solid " + HIST_DEF[k.k].color : "none" }} onClick={() => setInd(k.k)}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6, marginBottom: 8 }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--muted)" }}>{k.label}</span>
              {k.auto && <span style={badgeMini("var(--jade)")}>auto</span>}
              {k.derived && !k.auto && <span style={badgeMini("var(--slate)")}>calc</span>}
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 500, color: "var(--paper)" }}>{k.value}</div>
            <div style={{ marginTop: 6, fontFamily: "var(--font-mono)", fontSize: 10.5, color: k.delta == null ? "var(--muted-2)" : (k.delta >= 0 ? "var(--jade)" : "var(--clay)") }}>
              {k.delta == null ? "— sem base " + (ano - 1) : (k.delta >= 0 ? "▲ " : "▼ ") + Math.abs(k.delta).toFixed(1) + "% vs " + (ano - 1)}
            </div>
          </div>
        ))}
      </div>

      {editar && (
        <div style={{ marginBottom: 24, padding: "18px 20px", background: "var(--surface)", border: "1px solid var(--hairline-strong)", borderRadius: "var(--radius)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", marginBottom: 6 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <i data-lucide="pencil" style={{ width: 14, height: 14, strokeWidth: 1.7, color: "var(--brass)" }}></i>
              <span style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 500, color: "var(--paper)" }}>Dados manuais · {ano}</span>
            </div>
            <Select value={editU} onChange={setEditU} options={D.units} />
          </div>
          <p style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "var(--muted)", lineHeight: 1.6, margin: "0 0 14px", maxWidth: 760 }}>
            Preencha o que quiser sobrescrever. Onde o valor abaixo do mês mostra <b style={{ color: "var(--jade)", fontWeight: 500 }}>sistema</b>, o campo está vazio e usa o cálculo automático — apague para voltar ao sistema.
          </p>
          <div style={{ overflowX: "auto" }}>
            <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 720 }}>
              <thead>
                <tr>
                  <th style={thHist}>Mês</th>
                  {editInds.map((ei) => <th key={ei} style={thHist}>{HIST_DEF[ei].label}</th>)}
                </tr>
              </thead>
              <tbody>
                {D.meses.map((m, i) => (
                  <tr key={i}>
                    <td style={{ ...tdHist, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted-2)" }}>{m}</td>
                    {editInds.map((ei) => {
                      const ov = Number(ovU(ei)[i]) || 0;
                      const sys = sysU(ei)[i] || 0;
                      const sysShown = ei === "ticket" ? 0 : sys; // ticket: sistema = derivado, não mostrado como nº fixo
                      return (
                        <td key={ei} style={tdHist}>
                          <MoneyInput value={ov} onChange={(raw) => setManual(ei, i, raw)} face="mono" size={12} dashed align="right" width={80} accent={HIST_DEF[ei].color} />
                          <span style={{ display: "block", textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 8.5, color: ov ? "var(--muted-2)" : "var(--jade)", marginTop: 1 }}>
                            {ov ? "manual" : (sysShown ? "sistema " + HIST_DEF[ei].fmt(sysShown) : "sistema")}
                          </span>
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <div style={{ display: "flex", gap: 24, alignItems: "flex-start", flexWrap: "wrap" }}>
        <Panel title="Série histórica" style={{ flex: 2, minWidth: 440 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", marginBottom: 16, marginTop: -4 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase", color: def.color }}>{def.label}</span>
            <div style={{ maxWidth: "100%" }}>
              <SegTabs value={ind} onChange={setInd} options={window.HIST_INDS.map(k => ({ value: k, label: HIST_DEF[k].label.split(" ")[0] }))} />
            </div>
          </div>
          <LineSeries series={lineSeries} labels={D.meses} height={230} format={def.fmtFull} />
          <p style={{ fontFamily: "var(--font-body)", fontSize: 11, color: "var(--muted-2)", lineHeight: 1.6, margin: "14px 2px 0" }}>
            {ano} em destaque; anos anteriores tracejados para comparar a tendência. {ind === "fat" || ind === "vert" ? "Onde não há lançamento, usa o valor manual informado." : "Atendimentos e delivery vêm do preenchimento manual; ticket é faturamento ÷ atendimentos."}
          </p>
        </Panel>

        <Panel title="Ranking de unidades" action={<span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--muted-2)" }}>recebido {window.YEAR}</span>} style={{ flex: 1, minWidth: 300 }}>
          {ranking.every(r => r.v === 0)
            ? <p style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--muted-2)", textAlign: "center", padding: "30px 0" }}>Sem receitas recebidas ainda. Lance receitas na aba Faturamento.</p>
            : ranking.map((r, i) => (
              <div key={r.n} style={{ padding: "12px 0", borderTop: i === 0 ? "none" : "1px solid var(--hairline)" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 9, fontFamily: "var(--font-body)", fontSize: 13, color: "var(--paper)" }}>
                    <span style={{ fontFamily: "var(--font-display)", fontSize: 15, color: "var(--brass)", width: 16 }}>{i + 1}</span>{r.n}
                  </span>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--paper)" }}>{window.BRLk(r.v)}</span>
                </div>
                <div style={{ height: 8, borderRadius: 4, background: "var(--hairline)", overflow: "hidden" }}>
                  <div style={{ height: "100%", width: (r.v / rankMax * 100) + "%", background: r.c, transition: "width .5s ease" }}></div>
                </div>
              </div>
            ))}
        </Panel>
      </div>
    </div>
  );
}

const navMiniH = { width: 28, height: 28, borderRadius: "50%", background: "none", border: "none", display: "grid", placeItems: "center", cursor: "pointer", color: "var(--muted)" };
const badgeMini = (c) => ({ fontFamily: "var(--font-mono)", fontSize: 8, letterSpacing: "0.06em", textTransform: "uppercase", color: c, border: "1px solid var(--hairline)", borderRadius: 20, padding: "1px 6px" });
const thHist = { textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--muted)", padding: "0 6px 8px", whiteSpace: "nowrap" };
const tdHist = { textAlign: "right", padding: "4px 6px", verticalAlign: "top" };

window.Historico = Historico;
