/* ------------------------------------------------------------------ *
 *  Dashboard — KPI cards + 2 graphiques recharts
 * ------------------------------------------------------------------ */

function Dashboard({ rows, fraisDesign, prixEcosysteme, totaux, machineLabel }) {
  const { KpiCard, Icon, useDarkMode } = window;
  const { t, fmt, currencySymbol } = useLang();
  const [isDark] = useDarkMode();
  const Re = window.Recharts;

  const chartGrid = isDark ? '#232545' : '#EEEFF5';
  const laboBg    = isDark ? '#3D3F60' : '#B9BBCE';
  const axisColor = isDark ? '#5A5D7E' : '#7E81A0';
  const refLabel  = isDark ? '#A38FF7' : '#3B22B0';
  const {
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
    LineChart, Line, ReferenceLine, Legend, ReferenceDot
  } = Re;

  const economieMensuelleTotale = totaux.economieMois;
  const economieAnnuelle        = totaux.economieAn;
  const beneficeNetAn1          = economieAnnuelle - prixEcosysteme;
  const rentable                = economieMensuelleTotale > 0;
  const moisAvantROI            = rentable ? Math.ceil(prixEcosysteme / economieMensuelleTotale) : null;

  const laboKey   = t('dash.bar.labo');
  const interneKey = t('dash.bar.interne');

  const dataBarres = [{
    name: t('dash.bar.annual'),
    [laboKey]:    Math.round(totaux.coutLaboAn),
    [interneKey]: Math.round(totaux.coutInterneAn),
  }];

  const horizon = 36;
  const dataAmort = [];
  for (let m = 0; m <= horizon; m++) {
    dataAmort.push({
      mois: m,
      cumul: Math.round(m * economieMensuelleTotale),
      seuil: prixEcosysteme,
    });
  }
  const moisROIborne = (moisAvantROI != null && moisAvantROI <= horizon) ? moisAvantROI : null;

  return (
    <div className="space-y-5 fade-up">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <KpiCard
          label={t('dash.eco.label')}
          tone="brand"
          icon={<Icon.savings />}
          value={fmt.EUR(economieAnnuelle)}
          sub={t('dash.eco.sub')}
          helper={t('dash.eco.helper', fmt.EUR(economieMensuelleTotale))}
        />
        <KpiCard
          label={t('dash.ben.label')}
          tone={beneficeNetAn1 >= 0 ? 'success' : 'danger'}
          icon={<Icon.euro />}
          value={fmt.EUR(beneficeNetAn1)}
          sub={t('dash.ben.sub', fmt.EUR(prixEcosysteme))}
          helper={beneficeNetAn1 >= 0 ? t('dash.ben.helperPos') : t('dash.ben.helperNeg')}
        />
        <KpiCard
          label={t('dash.roi.label')}
          icon={<Icon.clock />}
          tone={rentable ? 'default' : 'warn'}
          value={rentable ? t('synth.gen.roiOk', moisAvantROI) : t('dash.roi.nd')}
          sub={rentable
            ? (moisAvantROI <= 12 ? t('dash.roi.sub12') : t('dash.roi.sub12+', fmt.dec1(moisAvantROI / 12)))
            : t('dash.roi.subNone')
          }
          helper={rentable
            ? t('dash.roi.helper', fmt.EUR(economieMensuelleTotale), moisAvantROI, machineLabel)
            : t('dash.roi.helperNone')}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <div className="bg-white border border-ink-200 rounded-2xl shadow-card p-5">
          <div className="flex items-start justify-between mb-2">
            <div>
              <h3 className="text-[13.5px] font-semibold text-ink-900">{t('dash.bar.title')}</h3>
              <p className="text-[12px] text-ink-500">{t('dash.bar.sub')}</p>
            </div>
            <Icon.chart />
          </div>
          <div className="h-56">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={dataBarres} margin={{ top: 12, right: 16, left: 0, bottom: 0 }} barCategoryGap={60}>
                <CartesianGrid strokeDasharray="3 3" stroke={chartGrid} vertical={false}/>
                <XAxis dataKey="name" tick={{ fontSize: 12, fill: axisColor }} axisLine={false} tickLine={false}/>
                <YAxis tick={{ fontSize: 11, fill: axisColor }} axisLine={false} tickLine={false}
                       tickFormatter={(v) => fmt.num(v) + ' ' + currencySymbol} width={70}/>
                <Tooltip formatter={(v) => fmt.EUR(v)} cursor={{ fill: 'rgba(91,61,245,0.04)'}}/>
                <Legend iconType="circle" wrapperStyle={{ fontSize: 12, paddingTop: 8, color: isDark ? '#8082A0' : undefined }}/>
                <Bar dataKey={laboKey}    fill={laboBg} radius={[8,8,0,0]} maxBarSize={64}/>
                <Bar dataKey={interneKey} fill="#5B3DF5" radius={[8,8,0,0]} maxBarSize={64}/>
              </BarChart>
            </ResponsiveContainer>
          </div>
          <div className="mt-3 grid grid-cols-2 gap-3 text-[12px]">
            <div className="rounded-lg bg-ink-50 p-2.5">
              <div className="text-ink-500">{t('dash.bar.laboShort')}</div>
              <div className="font-semibold tnum text-ink-900">{fmt.EUR(totaux.coutLaboAn)}</div>
            </div>
            <div className="rounded-lg bg-brand-50 p-2.5">
              <div className="text-brand-700">{t('dash.bar.interneShort')}</div>
              <div className="font-semibold tnum text-brand-700">{fmt.EUR(totaux.coutInterneAn)}</div>
            </div>
          </div>
        </div>

        <div className="bg-white border border-ink-200 rounded-2xl shadow-card p-5">
          <div className="flex items-start justify-between mb-2">
            <div>
              <h3 className="text-[13.5px] font-semibold text-ink-900">{t('dash.amort.title')}</h3>
              <p className="text-[12px] text-ink-500">{t('dash.amort.sub')}</p>
            </div>
            <Icon.flow />
          </div>
          <div className="h-56">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={dataAmort} margin={{ top: 12, right: 18, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke={chartGrid} vertical={false}/>
                <XAxis dataKey="mois"
                       tick={{ fontSize: 11, fill: axisColor }}
                       axisLine={false} tickLine={false}
                       tickFormatter={(v) => v + t('dash.amort.msuffix')}
                       ticks={[0,6,12,18,24,30,36]}/>
                <YAxis tick={{ fontSize: 11, fill: axisColor }} axisLine={false} tickLine={false}
                       tickFormatter={(v) => v >= 1000 ? (v/1000).toFixed(0) + 'k ' + currencySymbol : v + ' ' + currencySymbol} width={56}/>
                <Tooltip formatter={(v) => fmt.EUR(v)} labelFormatter={(l) => t('dash.amort.mois', l)}/>
                <Line type="monotone" dataKey="seuil" stroke={laboBg} strokeDasharray="4 4" strokeWidth={1.5} dot={false} name={t('dash.amort.seuil')}/>
                <Line type="monotone" dataKey="cumul" stroke="#5B3DF5" strokeWidth={2.5} dot={false} name={t('dash.amort.cumul')}/>
                {moisROIborne != null && (
                  <ReferenceDot x={moisROIborne} y={prixEcosysteme} r={5} fill="#5B3DF5" stroke="#fff" strokeWidth={2}
                                label={{ value: t('dash.amort.roi', moisROIborne), position: 'top', fill: refLabel, fontSize: 11, fontWeight: 600 }}/>
                )}
              </LineChart>
            </ResponsiveContainer>
          </div>
          <div className="mt-3 text-[12px] text-ink-500 flex items-center gap-2">
            {rentable
              ? <><span className="w-2 h-2 rounded-full bg-brand-500 shrink-0"></span>
                  {t('dash.amort.ok', moisAvantROI)}</>
              : <><span className="w-2 h-2 rounded-full bg-amber-500 shrink-0"></span>
                  {t('dash.amort.nok')}</>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
