// flow-freetime.jsx — Free-time clocks dashboard

const { ACTIVE_CLOCKS: FT_CLOCKS } = window.FLOW_DATA;

const TYPE_META = {
  demurrage: { label: 'Demurrage', icon: 'package',  color: 'var(--primary-700)' },
  detention: { label: 'Detention', icon: 'truck',    color: 'var(--warning-700)' },
  storage:   { label: 'Storage',   icon: 'warehouse',color: 'var(--ink-2)' },
  driver:    { label: 'Driver wait', icon: 'user',   color: 'var(--danger-700)' },
};

const formatHours = (h) => {
  const d = Math.floor(h / 24);
  const r = Math.round((h - d * 24) * 10) / 10;
  if (d > 0) return `${d}d ${Math.round(r)}h`;
  return `${r}h`;
};

const ClockRow = ({ c }) => {
  const pct = (c.usedHours / c.freeHours) * 100;
  const tone = pct >= 90 ? 'crit' : pct >= 70 ? 'warn' : 'ok';
  const meta = TYPE_META[c.type];
  const Ic = I[meta.icon] || I.clock;
  const remaining = c.freeHours - c.usedHours;
  const overage = remaining < 0;
  const expectedCharge = overage ? Math.abs(remaining) / 24 * c.ratePerDay : 0;

  return (
    <tr>
      <td>
        <div className="row gap-2" style={{ alignItems: 'center' }}>
          <div style={{ width: 28, height: 28, borderRadius: 7, background: 'var(--slate-50)', color: meta.color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Ic size={14} />
          </div>
          <div className="col">
            <div className="text-sm fw-600">{meta.label}</div>
            <div className="text-xs text-muted">{c.location}</div>
          </div>
        </div>
      </td>
      <td>
        <div className="col">
          <div className="mono text-sm fw-600">{c.shipment}</div>
          <div className="text-xs text-muted">{c.counterparty}</div>
        </div>
      </td>
      <td className="text-sm mono num">{c.started.slice(5,16)}</td>
      <td>
        <div className="col gap-2" style={{ minWidth: 200 }}>
          <FreeTimeBar usedHours={c.usedHours} freeHours={c.freeHours} />
          <div className="row gap-2" style={{ alignItems: 'center', justifyContent: 'space-between' }}>
            <div className="text-xs">
              <span className="fw-600 mono">{formatHours(c.usedHours)}</span>
              <span className="text-muted"> / {formatHours(c.freeHours)} free</span>
            </div>
            <div className="text-xs fw-600 mono" style={{
              color: tone === 'crit' ? 'var(--danger-700)' : tone === 'warn' ? 'var(--warning-700)' : 'var(--success)',
            }}>{Math.round(pct)}%</div>
          </div>
        </div>
      </td>
      <td className="text-sm mono num" style={{ textAlign: 'right' }}>€{c.ratePerDay}<span className="text-muted text-xs">/d</span></td>
      <td className="text-sm mono num fw-600" style={{ textAlign: 'right', color: overage ? 'var(--danger-700)' : 'var(--muted)' }}>
        {overage ? `€${Math.round(expectedCharge)}` : '€0'}
      </td>
      <td style={{ width: 1 }}>
        <div className="row gap-1">
          <button className="btn btn-xs">Open</button>
          <button className="btn btn-ghost btn-icon btn-xs"><I.more size={13}/></button>
        </div>
      </td>
    </tr>
  );
};

const Heatmap = () => {
  const types = ['demurrage', 'detention', 'storage', 'driver'];
  const counterparties = ['Maersk', 'Donau Logistik', 'COSCO', 'Anatolia Loj.', 'Sofia ICT', 'Rhône Cargo'];
  // synthetic intensities
  const matrix = [
    [3.2, 0.4, 4.8, 0,   0,   0  ],
    [0,   2.1, 0,   0.5, 0,   0.6],
    [0,   0,   0,   0,   0.9, 0  ],
    [0,   0,   0,   1.6, 0,   0  ],
  ];
  const max = Math.max(...matrix.flat(), 0.01);

  return (
    <Card style={{ padding: 16 }}>
      <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 12 }}>
        <div className="text-sm fw-600">Active accrual heatmap</div>
        <span className="text-xs text-muted">€/day · clock type × counterparty</span>
        <div className="flex-1" />
      </div>
      <div style={{ overflowX: 'auto' }}>
        <table style={{ borderCollapse: 'separate', borderSpacing: 4 }}>
          <thead>
            <tr>
              <th />
              {counterparties.map((c, i) => (
                <th key={i} className="text-xs text-muted" style={{ fontWeight: 500, padding: '4px 6px', writingMode: 'horizontal-tb', whiteSpace: 'nowrap', textAlign: 'left', maxWidth: 80 }}>{c}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {types.map((t, ti) => (
              <tr key={t}>
                <td className="text-xs fw-600" style={{ padding: '4px 8px 4px 0', whiteSpace: 'nowrap' }}>{TYPE_META[t].label}</td>
                {counterparties.map((c, ci) => {
                  const v = matrix[ti][ci];
                  const intensity = v / max;
                  const bg = v === 0 ? 'var(--surface-2)' :
                    intensity > 0.7 ? 'var(--danger)' :
                    intensity > 0.3 ? 'var(--warning)' : 'var(--success)';
                  return (
                    <td key={ci} style={{ padding: 0 }}>
                      <div style={{
                        width: 76, height: 38, borderRadius: 6,
                        background: v === 0 ? 'var(--surface-2)' : bg,
                        opacity: v === 0 ? 1 : 0.35 + intensity * 0.55,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        color: v === 0 ? 'var(--muted-2)' : 'white',
                        fontSize: 11.5, fontWeight: 600, fontFamily: 'var(--font-mono)',
                      }}>{v > 0 ? `€${(v * 100).toFixed(0)}` : '—'}</div>
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  );
};

const TopAtRisk = () => {
  const sorted = [...FT_CLOCKS].sort((a, b) => (b.usedHours / b.freeHours) - (a.usedHours / a.freeHours)).slice(0, 5);
  return (
    <Card style={{ padding: 16 }}>
      <div className="row gap-2" style={{ alignItems: 'center', marginBottom: 12 }}>
        <div className="text-sm fw-600">Top at-risk · 5</div>
        <div className="flex-1" />
        <span className="text-xs text-muted">closest to expiry</span>
      </div>
      <div className="col gap-3">
        {sorted.map((c) => {
          const pct = c.usedHours / c.freeHours * 100;
          const tone = pct >= 90 ? 'crit' : pct >= 70 ? 'warn' : 'ok';
          const meta = TYPE_META[c.type];
          return (
            <div key={c.id} className="col gap-2">
              <div className="row gap-2" style={{ alignItems: 'baseline' }}>
                <span className="badge badge-outline text-xs">{meta.label}</span>
                <span className="mono text-sm fw-600">{c.shipment}</span>
                <span className="text-xs text-muted ellipsis flex-1">{c.counterparty}</span>
                <span className="mono text-sm fw-600" style={{ color: tone === 'crit' ? 'var(--danger-700)' : tone === 'warn' ? 'var(--warning-700)' : 'var(--success)' }}>
                  {Math.round(pct)}%
                </span>
              </div>
              <FreeTimeBar usedHours={c.usedHours} freeHours={c.freeHours} height={8} />
            </div>
          );
        })}
      </div>
    </Card>
  );
};

const BurndownTrend = () => {
  // weekly demurrage spend trend, 12 weeks
  const data = [820, 1100, 940, 1320, 1860, 1480, 1620, 2240, 2680, 3140, 3680, 4180];
  const max = Math.max(...data) * 1.1;
  const W = 380, H = 140, P = 24;
  const dx = (W - P * 2) / (data.length - 1);
  const path = data.map((v, i) => `${i === 0 ? 'M' : 'L'} ${P + i * dx} ${H - P - (v / max) * (H - P * 2)}`).join(' ');
  const fill = `${path} L ${W - P} ${H - P} L ${P} ${H - P} Z`;
  return (
    <Card style={{ padding: 16 }}>
      <div className="row gap-2" style={{ marginBottom: 8, alignItems: 'baseline' }}>
        <div className="text-sm fw-600">Free-time burn — 12-week trend</div>
        <div className="flex-1" />
        <span className="text-xs text-muted">total: <b>€{data.reduce((a,b)=>a+b,0).toLocaleString()}</b></span>
      </div>
      <div className="row gap-3" style={{ alignItems: 'baseline', marginBottom: 4 }}>
        <div className="text-3xl fw-700 num" style={{ color: 'var(--danger-700)' }}>€{data[data.length - 1].toLocaleString()}</div>
        <div className="text-sm text-muted">this week ·</div>
        <div className="text-sm fw-600" style={{ color: 'var(--danger-700)' }}>+13.6%</div>
        <div className="text-sm text-muted">vs prior</div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 160, display: 'block' }}>
        <defs>
          <linearGradient id="ftGrad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="hsl(0 70% 55%)" stopOpacity="0.25" />
            <stop offset="1" stopColor="hsl(0 70% 55%)" stopOpacity="0" />
          </linearGradient>
        </defs>
        {[0.25, 0.5, 0.75, 1].map((g, i) => <line key={i} x1={P} x2={W - P} y1={H - P - g * (H - P * 2)} y2={H - P - g * (H - P * 2)} stroke="var(--border)" strokeDasharray="2 3" />)}
        <path d={fill} fill="url(#ftGrad)" />
        <path d={path} stroke="var(--danger)" strokeWidth="2" fill="none" />
        {data.map((v, i) => (
          <circle key={i} cx={P + i * dx} cy={H - P - (v / max) * (H - P * 2)} r={i === data.length - 1 ? 4 : 2.4} fill="var(--danger)" stroke="white" strokeWidth="1.5" />
        ))}
      </svg>
    </Card>
  );
};

const FreetimeDashboard = () => {
  const [tab, setTab] = useState('active');
  const [typeFilter, setTypeFilter] = useState('all');

  const totalDailyAccrual = FT_CLOCKS.filter((c) => c.usedHours / c.freeHours >= 0.7)
    .reduce((a, c) => a + c.ratePerDay, 0);
  const expectedLiability = FT_CLOCKS.reduce((a, c) => {
    const remaining = c.freeHours - c.usedHours;
    return a + (remaining < 0 ? Math.abs(remaining) / 24 * c.ratePerDay : 0);
  }, 0);

  const visible = FT_CLOCKS.filter((c) => typeFilter === 'all' || c.type === typeFilter);

  return (
    <div className="col" style={{ padding: '20px 24px', gap: 16 }}>
      <SectionHeader
        title="Free-time clocks"
        subtitle="Demurrage, detention, port storage and driver-waiting clocks across the network."
        right={
          <div className="row gap-2">
            <button className="btn btn-sm"><I.download size={14}/>Export</button>
            <button className="btn btn-sm"><I.bell size={14}/>Configure thresholds</button>
          </div>
        }
      />

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        <Card style={{ padding: 16 }}>
          <div className="text-xs text-muted fw-500" style={{ textTransform: 'uppercase', letterSpacing: '0.04em', fontSize: 10.5 }}>Active clocks</div>
          <div className="row gap-2" style={{ alignItems: 'baseline', marginTop: 6 }}>
            <div className="text-3xl fw-700 num">{FT_CLOCKS.length}</div>
            <div className="text-xs text-muted">running now</div>
          </div>
          <div className="row gap-2" style={{ marginTop: 8 }}>
            <span className="badge badge-success">3 ok</span>
            <span className="badge badge-warning">2 at-risk</span>
            <span className="badge badge-danger">1 critical</span>
          </div>
        </Card>
        <Card style={{ padding: 16 }}>
          <div className="text-xs text-muted fw-500" style={{ textTransform: 'uppercase', letterSpacing: '0.04em', fontSize: 10.5 }}>Daily accrual (at-risk)</div>
          <div className="row gap-2" style={{ alignItems: 'baseline', marginTop: 6 }}>
            <div className="text-3xl fw-700 num" style={{ color: 'var(--warning-700)' }}>€{totalDailyAccrual.toLocaleString()}</div>
            <div className="text-xs text-muted">/day</div>
          </div>
          <div className="text-xs text-muted" style={{ marginTop: 8 }}>If nothing changes in next 24h.</div>
        </Card>
        <Card style={{ padding: 16 }}>
          <div className="text-xs text-muted fw-500" style={{ textTransform: 'uppercase', letterSpacing: '0.04em', fontSize: 10.5 }}>Expected liability</div>
          <div className="row gap-2" style={{ alignItems: 'baseline', marginTop: 6 }}>
            <div className="text-3xl fw-700 num" style={{ color: 'var(--danger-700)' }}>€{Math.round(expectedLiability).toLocaleString()}</div>
            <div className="text-xs text-muted">if no action</div>
          </div>
          <div className="text-xs" style={{ marginTop: 8, color: 'var(--danger-700)' }}>+€840 in last 6 hours</div>
        </Card>
        <Card style={{ padding: 16 }}>
          <div className="text-xs text-muted fw-500" style={{ textTransform: 'uppercase', letterSpacing: '0.04em', fontSize: 10.5 }}>Recovered this month</div>
          <div className="row gap-2" style={{ alignItems: 'baseline', marginTop: 6 }}>
            <div className="text-3xl fw-700 num" style={{ color: 'var(--success)' }}>€2,180</div>
          </div>
          <div className="text-xs text-muted" style={{ marginTop: 8 }}>across 7 disputes won</div>
        </Card>
      </div>

      {/* Heatmap + top at-risk */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 12 }}>
        <Heatmap />
        <TopAtRisk />
      </div>

      {/* Trend */}
      <BurndownTrend />

      {/* Active clocks table */}
      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <div className="row gap-3" style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', alignItems: 'center' }}>
          <div className="tabs" style={{ borderBottom: 0, marginBottom: 0 }}>
            <div className={`tab ${tab === 'active' ? 'active' : ''}`} onClick={() => setTab('active')}>Active <span className="badge badge-ghost num">{FT_CLOCKS.length}</span></div>
            <div className={`tab ${tab === 'expired' ? 'active' : ''}`} onClick={() => setTab('expired')}>Expired & invoiced <span className="badge badge-ghost num">22</span></div>
            <div className={`tab ${tab === 'disputed' ? 'active' : ''}`} onClick={() => setTab('disputed')}>Disputed <span className="badge badge-ghost num">3</span></div>
          </div>
          <div className="flex-1" />
          <div className="row gap-1">
            {[
              { v: 'all', l: 'All' },
              { v: 'demurrage', l: 'Demurrage' },
              { v: 'detention', l: 'Detention' },
              { v: 'storage',   l: 'Storage' },
              { v: 'driver',    l: 'Driver' },
            ].map((o) => (
              <button key={o.v} className={`chip ${typeFilter === o.v ? 'active' : ''}`} onClick={() => setTypeFilter(o.v)}>{o.l}</button>
            ))}
          </div>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>Type / location</th>
              <th>Shipment</th>
              <th>Started</th>
              <th>Free-time progress</th>
              <th style={{ textAlign: 'right' }}>Rate</th>
              <th style={{ textAlign: 'right' }}>Accrued</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {visible.map((c) => <ClockRow key={c.id} c={c} />)}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

window.FreetimeDashboard = FreetimeDashboard;
