// Dashboard — vue d'ensemble de l'atelier

const DashboardPage = ({ setRoute }) => {
  const users = window.USERS || [];
  const projects = window.PROJECTS || [];
  const history = window.HISTORY || [];
  const monthly = window.MONTHLY || [];
  const activity = window.ACTIVITY || [];
  const me = window.USER_BY_ID?.(window.ME);

  const now = new Date();
  const week = isoWeek(now);
  const monthYear = new Intl.DateTimeFormat("fr-FR", { month: "long", year: "numeric" }).format(now);
  const dateLabel = new Intl.DateTimeFormat("fr-FR", { day: "numeric", month: "short", year: "numeric" })
    .format(now)
    .replace(".", "");
  const timeLabel = new Intl.DateTimeFormat("fr-FR", { hour: "2-digit", minute: "2-digit" }).format(now);

  const totalRev = history.reduce((a, h) => a + h.soldPrice, 0);
  const totalMargin = history.reduce((a, h) => a + (h.soldPrice - h.boughtPrice - h.expenses), 0);
  const totalClosedCost = history.reduce((a, h) => a + h.boughtPrice + h.expenses, 0);
  const inFlight = projects.length;
  const avgDays = history.length ? Math.round(history.reduce((a, h) => a + h.daysHeld, 0) / history.length) : 0;
  const avgMarginPct = totalClosedCost ? (totalMargin / totalClosedCost) * 100 : 0;
  const monthlyVolume = monthly.length ? monthly.reduce((a, m) => a + (m.deals || 0), 0) / monthly.length : 0;
  const currentMonth = monthly[monthly.length - 1] || { revenue: 0, expenses: 0, deals: 0 };
  const bestMonth = monthly.reduce((best, m) => m.revenue > best.revenue ? m : best, currentMonth);
  const chartMonthly = monthly.length > 1
    ? monthly
    : [
        { m: "Début", revenue: 0, expenses: 0 },
        { m: "Actuel", revenue: currentMonth.revenue, expenses: currentMonth.expenses },
      ];
  const stateCounts = projects.reduce((acc, p) => {
    acc[p.state] = (acc[p.state] || 0) + 1;
    return acc;
  }, {});
  const inFlightSummary = [
    stateCounts.listed ? `${stateCounts.listed} en vente` : null,
    stateCounts.ready ? `${stateCounts.ready} prête${stateCounts.ready > 1 ? "s" : ""}` : null,
    stateCounts.repair ? `${stateCounts.repair} en réparation` : null,
  ].filter(Boolean).join(" · ") || "aucune affaire ouverte";

  const revenueSpark = monthly.length > 1 ? monthly.map(m => m.revenue) : [0, totalRev];
  const marginSpark = monthly.length > 1 ? monthly.map(m => m.revenue - m.expenses) : [0, totalMargin];
  const revenueDelta = quarterDelta(monthly, m => m.revenue);
  const marginDelta = quarterDelta(monthly, m => m.revenue - m.expenses);

  const marginByCar = history.length
    ? history.map(h => ({
        label: h.title.split(" ").slice(0, 2).join(" "),
        value: h.soldPrice - h.boughtPrice - h.expenses,
      }))
    : [{ label: "Aucune", value: 0, muted: true }];

  const doneProjectExpenses = projects.flatMap(p => p.expenses || []).filter(e => e.done);
  const annexExpenses = doneProjectExpenses
    .filter(e => isAnnexExpense(e.label))
    .reduce((a, e) => a + e.cost, 0);
  const activeRepairExpenses = doneProjectExpenses
    .filter(e => !isAnnexExpense(e.label))
    .reduce((a, e) => a + e.cost, 0);
  const closedRepairExpenses = history.reduce((a, h) => a + h.expenses, 0);
  const vehicleSpend = history.reduce((a, h) => a + h.boughtPrice, 0) + projects.reduce((a, p) => a + p.boughtPrice, 0);

  const donut = [
    { label: "Achat véhicules", value: vehicleSpend, color: "oklch(0.74 0.13 150)" },
    { label: "Réparations / pièces", value: closedRepairExpenses + activeRepairExpenses, color: "oklch(0.62 0.11 150)" },
    { label: "Frais annexes (CT, mise en vente)", value: annexExpenses, color: "oklch(0.45 0.06 150)" },
  ];
  const dealCount = history.length + projects.length;

  return (
    <>
      <Topbar
        crumbs={["Atelier", "Dashboard"]}
        actions={
          <button type="button" className="tb-btn tb-btn-primary" onClick={() => setRoute({ page: "propositions" })}>
            <Icon name="plus" size={14} /> Nouvelle proposition
          </button>
        }
      />
      <div className="content">
        <div className="content-wide">
          <div className="hstack" style={{ marginBottom: 8 }}>
            <div>
              <div className="h1">Bonjour {me?.name || "l'équipe"} 👋</div>
              <div className="muted" style={{ marginTop: 4 }}>
                Voici ce qu'il se passe à l'atelier — semaine {week} · {monthYear}
              </div>
            </div>
            <div className="grow" />
            <div className="badge plain mono muted">{dateLabel} · {timeLabel}</div>
          </div>

          <div className="grid grid-4" style={{ marginTop: 18 }}>
            <StatCard
              label="CA cumulé"
              value={window.fmt.eur(totalRev)}
              delta={revenueDelta.label}
              positive={revenueDelta.positive}
              sparkData={revenueSpark}
            />
            <StatCard
              label="Bénéfice net"
              value={window.fmt.eur(totalMargin)}
              delta={marginDelta.label}
              positive={marginDelta.positive}
              sparkData={marginSpark}
              sub={`${history.length} affaire${history.length !== 1 ? "s" : ""} soldée${history.length !== 1 ? "s" : ""}`}
            />
            <StatCard
              label="Affaires en cours"
              value={inFlight}
              sub={inFlightSummary}
              icon="car"
            />
            <StatCard
              label="Durée moyenne"
              value={`${avgDays} j`}
              sub="entre achat & revente"
              icon="clock"
            />
          </div>

          <div className="grid grid-dash" style={{ marginTop: 18 }}>
            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">Revenus & dépenses</div>
                  <div className="card-sub">6 derniers mois · EUR</div>
                </div>
                <div className="hstack" style={{ gap: 14, fontSize: 11.5 }}>
                  <span className="hstack" style={{ gap: 6 }}>
                    <span style={{ width: 10, height: 2, background: "var(--accent)", borderRadius: 2 }}></span>
                    <span className="muted">Revenus</span>
                  </span>
                  <span className="hstack" style={{ gap: 6 }}>
                    <span style={{ width: 10, height: 0, borderTop: "1.5px dashed var(--fg-4)" }}></span>
                    <span className="muted">Dépenses</span>
                  </span>
                </div>
              </div>
              <div className="chart-wrap" style={{ paddingTop: 14 }}>
                <LineAreaChart data={chartMonthly} height={220} />
              </div>
              <div className="kpi-row" style={{ borderTop: "1px solid var(--border-soft)" }}>
                <div className="kpi"><span className="kpi-lbl">Mois en cours</span><span className="kpi-val">{window.fmt.eur(currentMonth.revenue)}</span></div>
                <div className="kpi"><span className="kpi-lbl">Meilleur mois</span><span className="kpi-val">{window.fmt.eur(bestMonth.revenue)}</span></div>
                <div className="kpi"><span className="kpi-lbl">Marge moy.</span><span className="kpi-val">{formatSignedPct(avgMarginPct)}</span></div>
                <div className="kpi"><span className="kpi-lbl">Volume / mois</span><span className="kpi-val">{monthlyVolume.toFixed(1)}</span></div>
              </div>
            </div>

            <div className="card">
              <div className="card-head">
                <div className="card-title">Répartition des dépenses</div>
                <Badge tone="plain"><span className="mono">{dealCount} affaire{dealCount !== 1 ? "s" : ""}</span></Badge>
              </div>
              <Donut data={donut} size={150} />
            </div>
          </div>

          <div className="grid grid-dash" style={{ marginTop: 18 }}>
            <div className="card">
              <div className="card-head">
                <div className="card-title">Bénéfice par véhicule revendu</div>
                <div className="hstack mono muted-2" style={{ fontSize: 11 }}>+ marge en €</div>
              </div>
              <div className="chart-wrap"><BarChart data={marginByCar} height={180} /></div>
            </div>

            <div className="card">
              <div className="card-head">
                <div className="card-title">Solde par associé</div>
                <div className="card-sub">cumulé</div>
              </div>
              <div style={{ padding: "4px 18px 18px" }}>
                {users.map(u => {
                  const inv = history.reduce((a, h) => a + (h.investments[u.id] || 0), 0);
                  const totalInvest = history.reduce((a, h) => a + Object.values(h.investments).reduce((b,c)=>b+c, 0), 0);
                  const ratio = totalInvest ? inv / totalInvest : 0;
                  const profit = history.reduce((a, h) => {
                    const tot = Object.values(h.investments).reduce((b,c)=>b+c, 0);
                    return tot ? a + ((h.investments[u.id] || 0) / tot) * (h.soldPrice - h.boughtPrice - h.expenses) : a;
                  }, 0);
                  return (
                    <div key={u.id} className="vote-row">
                      <div className="vote-name">
                        <Avatar id={u.id} />
                        <span>{u.name}</span>
                      </div>
                      <div className="vote-bar-wrap">
                        <div className="vote-bar-fill" style={{ width: `${ratio * 100}%` }}></div>
                      </div>
                      <div className="vote-amt pos" style={{ color: "var(--pos)" }}>+ {window.fmt.eur(profit)}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          <div className="grid grid-dash" style={{ marginTop: 18 }}>
            <div className="card">
              <div className="card-head">
                <div className="card-title">Affaires en cours</div>
                <button className="btn btn-sm btn-ghost" onClick={() => setRoute({ page: "projects" })}>
                  Tout voir <Icon name="chev_r" size={12} />
                </button>
              </div>
              <table className="table">
                <thead>
                  <tr>
                    <th>Véhicule</th>
                    <th>État</th>
                    <th>Associés</th>
                    <th className="right">Achat</th>
                    <th className="right">Marge proj.</th>
                  </tr>
                </thead>
                <tbody>
                  {projects.map(p => {
                    const t = window.projectTotals(p);
                    return (
                      <tr key={p.id} className="clickable" onClick={() => setRoute({ page: "projectDetail", id: p.id })}>
                        <td>
                          <div style={{ fontWeight: 500 }}>{p.title}</div>
                          <div className="muted mono" style={{ fontSize: 11 }}>{p.year} · {window.fmt.km(p.km)}</div>
                        </td>
                        <td><Badge tone={window.STATES[p.state].cls}>{window.STATES[p.state].label}</Badge></td>
                        <td><AvatarGroup ids={Object.keys(p.investments)} /></td>
                        <td className="right num">{window.fmt.eur(p.boughtPrice)}</td>
                        <td className="right num" style={{ color: t.projMargin > 0 ? "var(--pos)" : "var(--neg)" }}>
                          {t.projMargin >= 0 ? "+" : ""}{window.fmt.eur(t.projMargin)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            <div className="card">
              <div className="card-head">
                <div className="card-title">Activité récente</div>
                <button type="button" className="btn btn-sm btn-ghost" onClick={() => window.AppUI?.notice("Le journal complet arrive bientôt.")}>
                  <Icon name="chev_r" size={12} />
                </button>
              </div>
              <div style={{ padding: "8px 18px 14px" }}>
                {activity.map((a, i) => (
                  <div key={i} className="comment" style={{ padding: "10px 0" }}>
                    <Avatar id={a.who} size={28} />
                    <div className="comment-body">
                      <div className="comment-text">
                        <strong>{window.USER_BY_ID(a.who).name}</strong> <span className="muted">{a.what}</span>{" "}
                        <span style={{ fontWeight: 500 }}>{a.item}</span>
                      </div>
                      <div className="comment-time">{a.when}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

function isoWeek(date) {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  const day = d.getUTCDay() || 7;
  d.setUTCDate(d.getUTCDate() + 4 - day);
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
}

function quarterDelta(months, getValue) {
  if (months.length < 4) return { label: null, positive: true };
  const current = months.slice(-3).reduce((a, m) => a + getValue(m), 0);
  const previous = months.slice(-6, -3).reduce((a, m) => a + getValue(m), 0);
  if (!previous) return { label: "nouveau trim.", positive: current >= 0 };
  const delta = ((current - previous) / Math.abs(previous)) * 100;
  return {
    label: `${delta >= 0 ? "+" : ""}${delta.toFixed(1)} % vs trim. dern.`,
    positive: delta >= 0,
  };
}

function formatSignedPct(value) {
  return `${value >= 0 ? "+" : ""}${Math.round(value)} %`;
}

function isAnnexExpense(label = "") {
  const normalized = label.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  return /(ct|controle|contre-visite|annonce|mise en vente|carte grise|immatriculation|administratif)/.test(normalized);
}

window.PAGES = window.PAGES || {};
window.PAGES.dashboard = DashboardPage;
