// BinGest dashboard mock — used in hero (compact) and demo tour (full).
// Includes data-hotspot anchors so a parent can render highlight overlays.

const DM_NAV = [
{ id: "dashboard", label: "Dashboard", Icon: IconDashboard, active: true },
{ id: "clientes", label: "Clientes", Icon: IconUsers },
{ id: "folha", label: "Folha de ponto", Icon: IconClock },
{ id: "obras", label: "Obras", Icon: IconBuilding, sub: "Condomínio das Acácias" },
{ id: "servicos", label: "Serviços", Icon: IconClipboard },
{ id: "equipe", label: "Equipe", Icon: IconTeam },
{ id: "financeiro", label: "Financeiro", Icon: IconWallet },
{ id: "relatorios", label: "Relatórios", Icon: IconReport },
{ id: "config", label: "Configurações", Icon: IconGear }];


const DM_TABS = ["Consolidado", "Somente Obras", "Somente Assistência Técnica", "Por Cliente"];

function brl(n) {
  return "R$ " + n.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

// Animated currency that ticks up to the target on mount or when value changes.
function TickNumber({ value, prefix = "R$ ", suffix = "", duration = 1200, decimals = 2 }) {
  const [n, setN] = React.useState(0);
  const startedRef = React.useRef(false);
  React.useEffect(() => {
    let raf, t0;
    const from = 0,to = value;
    const step = (t) => {
      if (!t0) t0 = t;
      const p = Math.min(1, (t - t0) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(from + (to - from) * eased);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  const formatted = decimals ?
  n.toLocaleString("pt-BR", { minimumFractionDigits: decimals, maximumFractionDigits: decimals }) :
  Math.round(n).toLocaleString("pt-BR");
  return <span className="tabular">{prefix}{formatted}{suffix}</span>;
}

// Bar chart — last 6 months: Receita Obras (blue), Custo Direto (amber), Receita AT (purple), Resultado Op (green)
function MiniBarChart({ height = 180 }) {
  const months = ["dez. 25", "jan. 26", "fev. 26", "mar. 26", "abr. 26", "mai. 26"];
  const obras = [3200, 0, 5800, 0, 7800, 19500];
  const at = [0, 2400, 0, 1800, 0, 0];
  const custo = [-1100, -800, -2200, -700, -2800, -8210];
  const resOp = [2100, 1600, 3600, 1100, 5000, 11290];
  const all = [...obras, ...at, ...resOp];
  const max = Math.max(...all);
  const w = 560,h = height;
  const gx = 36,gy = 18;
  const innerW = w - gx - 8,innerH = h - gy - 24;
  const groupW = innerW / months.length;
  const barW = 8;
  const colors = { obras: "#2A5BFF", at: "#7C5BD8", custo: "#F59E0B", res: "#16A34A" };
  const scale = (v) => v / max * innerH;
  const yTicks = [0, 5000, 10000, 15000, 20000];

  return (
    <svg className="dm-chart-svg" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      {yTicks.map((t, i) => {
        const y = h - gy - t / max * innerH;
        return (
          <g key={i}>
            <line x1={gx} y1={y} x2={w - 4} y2={y} stroke="#E3E7EF" strokeDasharray="3 3" />
            <text x={gx - 4} y={y + 3} fontSize="9" textAnchor="end" fill="#8892A8">R${t / 1000}k</text>
          </g>);

      })}
      {months.map((m, i) => {
        const cx = gx + groupW * (i + 0.5);
        const vals = [
        { v: custo[i], color: colors.custo, off: -1.5 },
        { v: at[i], color: colors.at, off: -0.5 },
        { v: obras[i], color: colors.obras, off: 0.5 },
        { v: resOp[i], color: colors.res, off: 1.5 }];

        return (
          <g key={m}>
            {vals.map((b, k) => {
              const v = Math.abs(b.v);
              const bh = scale(v);
              const x = cx + b.off * (barW + 1) - barW / 2;
              const y = h - gy - bh;
              return v === 0 ?
              null :
              <rect key={k} x={x} y={y} width={barW} height={bh} rx="2" fill={b.color} />;
            })}
            <text x={cx} y={h - 6} fontSize="9.5" textAnchor="middle" fill="#5C6680">{m}</text>
          </g>);

      })}
    </svg>);

}

function DashboardMock({ mode = "full", highlight = null, animateValues = true, scale = 1 }) {
  const rootRef = React.useRef(null);
  const [box, setBox] = React.useState(null);

  // Compute highlight bbox relative to mock root
  React.useEffect(() => {
    if (!highlight || !rootRef.current) {setBox(null);return;}
    const el = rootRef.current.querySelector(`[data-hotspot="${highlight}"]`);
    if (!el) {setBox(null);return;}
    const rect = el.getBoundingClientRect();
    const root = rootRef.current.getBoundingClientRect();
    setBox({
      top: rect.top - root.top - 6,
      left: rect.left - root.left - 6,
      width: rect.width + 12,
      height: rect.height + 12
    });
  }, [highlight, mode]);

  // Recompute on resize
  React.useEffect(() => {
    if (!highlight || !rootRef.current) return;
    const ro = new ResizeObserver(() => {
      const el = rootRef.current.querySelector(`[data-hotspot="${highlight}"]`);
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const root = rootRef.current.getBoundingClientRect();
      setBox({
        top: rect.top - root.top - 6,
        left: rect.left - root.left - 6,
        width: rect.width + 12,
        height: rect.height + 12
      });
    });
    ro.observe(rootRef.current);
    return () => ro.disconnect();
  }, [highlight]);

  return (
    <div ref={rootRef} className={`dm ${mode === "compact" ? "compact" : ""}`}>
      {/* Sidebar */}
      <aside className="dm-side">
        <div className="dm-brand">
          <IconLogo size={26} />
          <span>BinGest</span>
        </div>
        <nav className="dm-nav">
          {DM_NAV.map((it) =>
          <React.Fragment key={it.id}>
              <div
              className={`dm-nav-item ${it.active ? "is-active" : ""}`}
              data-hotspot={`nav-${it.id}`}>
              
                <it.Icon size={16} />
                <span>{it.label}</span>
              </div>
              {it.sub && <div className="dm-nav-sub">{it.sub}</div>}
            </React.Fragment>
          )}
        </nav>
        <div className="dm-side-foot">
          <span>v0.1.0</span>
          <span>‹ Recolher</span>
        </div>
      </aside>

      {/* Main */}
      <div className="dm-main">
        <div className="dm-top">
          <div className="dm-crumbs">BinGest Construções</div>
          <div className="dm-user">
            <span className="dm-avatar">BG</span>
            <span>bingestapp@bingest.com</span>
            <IconChevronDown size={14} />
          </div>
        </div>

        <div className="dm-hello">
          <div>
            <h1>Olá, Fulano</h1>
            <p>BinGest Construções · quarta-feira, 13 de maio</p>
          </div>
          <button className="dm-export"><IconDownload size={15} /> Exportar DRE</button>
        </div>

        <div className="dm-tabs">
          {DM_TABS.map((t, i) =>
          <div key={t} className={`dm-tab ${i === 0 ? "is-active" : ""}`}>{t}</div>
          )}
        </div>

        {/* KPIs */}
        <div className="dm-kpis" data-hotspot="kpis">
          <div className="dm-kpi">
            <div className="dm-kpi-label">Obras Ativas</div>
            <div className="dm-kpi-val tabular">1</div>
          </div>
          <div className="dm-kpi">
            <div className="dm-kpi-label">Funcionários Ativos</div>
            <div className="dm-kpi-val tabular">2</div>
          </div>
          <div className="dm-kpi">
            <div className="dm-kpi-label">Receita Bruta Total</div>
            <div className="dm-kpi-val green tabular">
              {animateValues ? <TickNumber value={19500} /> : "R$ 19.500,00"}
            </div>
            <div className="dm-kpi-sub">maio de 2026</div>
          </div>
          <div className="dm-kpi" data-hotspot="resultado">
            <div className="dm-kpi-label">Resultado Operacional</div>
            <div className="dm-kpi-val tabular">
              {animateValues ? <TickNumber value={11290} /> : "R$ 11.290,00"}
            </div>
            <div className="dm-kpi-sub">57,9%</div>
          </div>
        </div>

        {/* Soft cards */}
        <div className="dm-soft-row">
          <div className="dm-soft blue" data-hotspot="obras-soft">
            <div className="dm-soft-icon"><IconBuilding size={18} /></div>
            <div>
              <div className="dm-soft-l1">Obras</div>
              <div className="dm-soft-l2 tabular">R$ 19.500,00</div>
              <div className="dm-soft-l3">Margem bruta 57.9%</div>
            </div>
          </div>
          <div className="dm-soft purple" data-hotspot="at-soft">
            <div className="dm-soft-icon"><IconHelmet size={18} /></div>
            <div>
              <div className="dm-soft-l1">Assistência Técnica</div>
              <div className="dm-soft-l2 tabular">R$ 0,00</div>
              <div className="dm-soft-l3">Margem bruta 0.0%</div>
            </div>
          </div>
        </div>

        {/* DRE + Chart */}
        <div className="dm-grid">
          <div className="dm-dre" data-hotspot="dre">
            <div className="dm-dre-head">
              <span>DRE Consolidado</span>
              <span>% Rec.</span>
              <span>Valor</span>
            </div>
            <div className="dm-dre-row total">
              <span className="lbl">Receita Bruta Total</span>
              <span className="right pct"></span>
              <span className="right">R$ 19.500,00</span>
            </div>
            <div className="dm-dre-row indent">
              <span className="lbl">Obras</span>
              <span className="right pct"></span>
              <span className="right">R$ 19.500,00</span>
            </div>
            <div className="dm-dre-row total pct-neg neg">
              <span className="lbl">(−) Custos Diretos Totais</span>
              <span className="right pct">−42.1%</span>
              <span className="right">−R$ 8.210,00</span>
            </div>
            <div className="dm-dre-row indent neg">
              <span className="lbl">Equipe Obras</span>
              <span className="right pct"></span>
              <span className="right">−R$ 8.210,00</span>
            </div>
            <div className="dm-dre-row total pct-pos">
              <span className="lbl">= Lucro Bruto</span>
              <span className="right pct">57.9%</span>
              <span className="right">R$ 11.290,00</span>
            </div>
            <div className="dm-dre-row total pct-pos">
              <span className="lbl">= Resultado Operacional</span>
              <span className="right pct">57.9%</span>
              <span className="right">R$ 11.290,00</span>
            </div>
          </div>

          <div className="dm-chart" data-hotspot="chart">
            <div className="dm-chart-title">Evolução — últimos 6 meses</div>
            <MiniBarChart height={mode === "compact" ? 140 : 180} />
            <div className="dm-chart-legend">
              <span><span className="dm-chart-dot" style={{ background: "#F59E0B" }}></span>Custo Dir. Total</span>
              <span><span className="dm-chart-dot" style={{ background: "#7C5BD8" }}></span>Rec. AT</span>
              <span><span className="dm-chart-dot" style={{ background: "#2A5BFF" }}></span>Rec. Obras</span>
              <span><span className="dm-chart-dot" style={{ background: "#16A34A" }}></span>Resultado Op.</span>
            </div>
          </div>
        </div>

        {/* Per-obra */}
        <div className="dm-obra" data-hotspot="obra-table">
          <div className="dm-obra-head">Resultado por Obra — Maio de 2026</div>
          <div className="dm-obra-row">
            <span className="lbl">Condomínio das Acácias</span>
            <span className="num">R$ 19.500,00</span>
            <span className="num">−R$ 8.210,00</span>
            <span className="num green">R$ 11.290,00</span>
          </div>
        </div>
      </div>

      {/* Highlight overlay */}
      {box &&
      <div className="dm-spot show pulse" style={{
        top: box.top, left: box.left, width: box.width, height: box.height
      }}>
          <div className="dm-spot-pin">!</div>
        </div>
      }
    </div>);

}

Object.assign(window, { DashboardMock, TickNumber, MiniBarChart, brl });