// Dashboard.jsx
(function () {
  const { useState, useEffect, useRef } = React;

  // ── Helpers ──────────────────────────────────────────────────────
  function fmtVal(v, unit) {
    if (unit === 'zł') {
      if (v >= 1000000) return (v / 1000000).toFixed(2).replace('.',',') + ' M zł';
      if (v >= 1000) return Math.round(v / 1000) + ' k zł';
      return v + ' zł';
    }
    if (unit === '%') return v.toFixed(1).replace('.',',') + '%';
    return v.toLocaleString('pl-PL');
  }

  function fmtNum(v, unit) {
    if (unit === 'zł') {
      if (v >= 1000000) return (v / 1000000).toFixed(2).replace('.',',') + ' M';
      if (v >= 1000) return Math.round(v / 1000) + ' k';
      return Math.round(v).toLocaleString('pl-PL');
    }
    if (unit === '%') return v.toFixed(1).replace('.',',');
    return Math.round(v).toLocaleString('pl-PL');
  }

  // ── CountUp hook ────────────────────────────────────────────────
  function useCountUp(target, duration = 1400) {
    const [val, setVal] = useState(0);
    useEffect(() => {
      let raf;
      const t0 = performance.now();
      const tick = (now) => {
        const p = Math.min((now - t0) / duration, 1);
        const e = 1 - Math.pow(1 - p, 3);
        setVal(e * target);
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
      return () => cancelAnimationFrame(raf);
    }, [target]);
    return val;
  }

  // ── Glass Tooltip ───────────────────────────────────────────────
  function GlassTooltip({ active, payload, label, unit }) {
    if (!active || !payload?.length) return null;
    return (
      <div style={{
        background: 'var(--bg-solid)', border: '1px solid var(--bdr2)',
        borderRadius: 12, padding: '10px 14px',
        boxShadow: '0 8px 32px rgba(0,0,0,0.35)',
      }}>
        <div style={{ fontSize: 11, color: 'var(--t3)', marginBottom: 4 }}>{label}</div>
        {payload.map((p, i) => (
          <div key={i} style={{ fontSize: 14, fontWeight: 700, color: p.color || '#7C5CFF' }}>
            {fmtVal(p.value, unit || 'zł')}
          </div>
        ))}
      </div>
    );
  }

  // ── Sparkline ───────────────────────────────────────────────────
  function Sparkline({ data, color }) {
    const { AreaChart, Area, ResponsiveContainer } = window.Recharts || {};
    const d = data.map((v, i) => ({ v, i }));
    const gradId = 'sg' + color.replace(/[^a-z0-9]/gi, '');
    return (
      <ResponsiveContainer width="100%" height={44}>
        <AreaChart data={d} margin={{ top: 2, right: 0, left: 0, bottom: 2 }}>
          <defs>
            <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%"  stopColor={color} stopOpacity={0.35} />
              <stop offset="95%" stopColor={color} stopOpacity={0}    />
            </linearGradient>
          </defs>
          <Area type="monotone" dataKey="v" stroke={color} fill={`url(#${gradId})`} strokeWidth={1.8} dot={false} isAnimationActive={false} />
        </AreaChart>
      </ResponsiveContainer>
    );
  }

  // ── KPI Card ────────────────────────────────────────────────────
  function KPICard({ kpi }) {
    const animated = useCountUp(kpi.value);
    const up = kpi.trend >= 0;
    return (
      <div className="glass-card" style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 6, position: 'relative', overflow: 'hidden' }}>
        {/* glow blob */}
        <div style={{ position: 'absolute', top: -30, right: -30, width: 100, height: 100, borderRadius: '50%', background: kpi.color, opacity: 0.08, filter: 'blur(30px)', pointerEvents: 'none' }} />

        <div style={{ fontSize: 12, color: 'var(--t2)', fontWeight: 500, letterSpacing: 0.3 }}>{kpi.label}</div>
        <div style={{ fontSize: 26, fontWeight: 800, color: 'var(--t1)', lineHeight: 1, letterSpacing: -1 }}>
          {fmtNum(animated, kpi.unit)}
          {kpi.unit === '%' && <span style={{ fontSize: 16 }}>%</span>}
          {kpi.unit === 'zł' && <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--t2)', marginLeft: 4 }}>zł</span>}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 12 }}>
          <span style={{
            padding: '2px 7px', borderRadius: 99, fontWeight: 600,
            background: up ? 'rgba(34,197,94,.15)' : 'rgba(239,68,68,.15)',
            color: up ? '#22C55E' : '#EF4444',
          }}>
            {up ? '↑' : '↓'} {Math.abs(kpi.trend).toFixed(1).replace('.',',')}%
          </span>
          <span style={{ color: 'var(--t3)' }}>vs poprzedni okres</span>
        </div>
        <Sparkline data={kpi.sparkline} color={kpi.color} />
      </div>
    );
  }

  // ── Main Sales Chart ────────────────────────────────────────────
  function SalesChart({ data }) {
    const { AreaChart, Area, ResponsiveContainer, XAxis, YAxis, Tooltip, CartesianGrid } = window.Recharts || {};
    const [period, setPeriod] = useState('30d');
    const d = data[period];
    return (
      <div className="glass-card" style={{ padding: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--t1)' }}>Sprzedaż w czasie</div>
            <div style={{ fontSize: 12, color: 'var(--t3)', marginTop: 2 }}>Przychód vs poprzedni okres</div>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            {['7d','30d','12m'].map(p => (
              <button key={p} onClick={() => setPeriod(p)} style={{
                padding: '5px 12px', borderRadius: 8, border: '1px solid var(--bdr)',
                background: period === p ? 'rgba(124,92,255,.2)' : 'var(--bg1)',
                color: period === p ? '#7C5CFF' : 'var(--t2)',
                fontWeight: period === p ? 600 : 400, fontSize: 12,
                cursor: 'pointer', outline: 'none', transition: 'all .15s',
                boxShadow: period === p ? 'inset 0 0 0 1px rgba(124,92,255,.4)' : 'none',
              }}>{p.toUpperCase()}</button>
            ))}
          </div>
        </div>
        <ResponsiveContainer width="100%" height={220}>
          <AreaChart data={d} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
            <defs>
              <linearGradient id="gradMain" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%"  stopColor="#7C5CFF" stopOpacity={0.3} />
                <stop offset="95%" stopColor="#7C5CFF" stopOpacity={0}   />
              </linearGradient>
              <linearGradient id="gradPrev" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%"  stopColor="#4DA3FF" stopOpacity={0.15} />
                <stop offset="95%" stopColor="#4DA3FF" stopOpacity={0}    />
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" vertical={false} />
            <XAxis dataKey="date" tick={{ fill: 'var(--t3)', fontSize: 11 }} axisLine={false} tickLine={false} interval={period==='30d'?5:'preserveStartEnd'} />
            <YAxis tick={{ fill: 'var(--t3)', fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={v => v >= 1000 ? `${v/1000}k` : v} width={42} />
            <Tooltip content={<GlassTooltip unit="zł" />} cursor={{ stroke:'rgba(124,92,255,.25)', strokeWidth:1 }} />
            <Area type="monotone" dataKey="prev"  stroke="#4DA3FF" fill="url(#gradPrev)" strokeWidth={1.5} dot={false} strokeDasharray="4 2" />
            <Area type="monotone" dataKey="value" stroke="#7C5CFF" fill="url(#gradMain)" strokeWidth={2.5} dot={false}
              style={{ filter: 'drop-shadow(0 0 6px rgba(124,92,255,0.5))' }} />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    );
  }

  // ── Donut Chart ─────────────────────────────────────────────────
  function DonutChart({ data }) {
    const { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } = window.Recharts || {};
    const RADIAN = Math.PI / 180;
    const total = data.reduce((s, d) => s + d.value, 0);
    return (
      <div className="glass-card" style={{ padding: 20 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--t1)', marginBottom: 4 }}>Leady wg źródła</div>
        <div style={{ fontSize: 11, color: 'var(--t3)', marginBottom: 12 }}>Łącznie {total}%</div>
        <ResponsiveContainer width="100%" height={160}>
          <PieChart>
            <Pie data={data} innerRadius={48} outerRadius={72} paddingAngle={3} dataKey="value" strokeWidth={0} animationBegin={300}>
              {data.map((d, i) => <Cell key={i} fill={d.color} />)}
            </Pie>
            <Tooltip content={({ active, payload }) => {
              if (!active || !payload?.length) return null;
              const p = payload[0].payload;
              return (
                <div style={{ background:'var(--bg-solid)', border:'1px solid var(--bdr2)', borderRadius:10, padding:'8px 12px', fontSize:13 }}>
                  <span style={{ color: p.color, fontWeight:700 }}>{p.name}: {p.value}%</span>
                </div>
              );
            }} />
          </PieChart>
        </ResponsiveContainer>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 4 }}>
          {data.map((d, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
              <div style={{ width: 8, height: 8, borderRadius: 2, background: d.color, flexShrink: 0 }} />
              <span style={{ color: 'var(--t2)', flex: 1 }}>{d.name}</span>
              <span style={{ color: 'var(--t1)', fontWeight: 600 }}>{d.value}%</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── Goal Gauge ──────────────────────────────────────────────────
  function GoalGauge({ value }) {
    const { RadialBarChart, RadialBar, ResponsiveContainer } = window.Recharts || {};
    const animated = useCountUp(value);
    const d = [{ value: Math.round(animated), fill: '#7C5CFF' }, { value: 100 - Math.round(animated), fill: 'rgba(124,92,255,0.08)' }];
    return (
      <div className="glass-card" style={{ padding: 20, textAlign: 'center' }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--t1)', marginBottom: 4 }}>Cel miesięczny</div>
        <div style={{ fontSize: 11, color: 'var(--t3)', marginBottom: 8 }}>Realizacja planu Q2</div>
        <div style={{ position: 'relative', display: 'inline-block' }}>
          <ResponsiveContainer width={140} height={140}>
            <RadialBarChart innerRadius={40} outerRadius={65} data={[{ value: Math.round(animated), fill:'url(#goalGrad)' }]} startAngle={225} endAngle={-45}>
              <defs>
                <linearGradient id="goalGrad" x1="0" y1="0" x2="1" y2="0">
                  <stop offset="0%"   stopColor="#7C5CFF" />
                  <stop offset="100%" stopColor="#4DA3FF" />
                </linearGradient>
              </defs>
              <RadialBar dataKey="value" cornerRadius={8} background={{ fill: 'rgba(255,255,255,0.04)' }} />
            </RadialBarChart>
          </ResponsiveContainer>
          <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--t1)', lineHeight: 1 }}>{Math.round(animated)}%</div>
            <div style={{ fontSize: 10, color: 'var(--t3)', marginTop: 2 }}>wykonania</div>
          </div>
        </div>
      </div>
    );
  }

  // ── Activity Feed ───────────────────────────────────────────────
  function ActivityFeed({ items }) {
    return (
      <div className="glass-card" style={{ padding: 20 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--t1)', marginBottom: 16 }}>Ostatnia aktywność</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
          {items.map((a, i) => (
            <div key={a.id} style={{ display: 'flex', gap: 12, paddingBottom: i < items.length-1 ? 14 : 0 }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 0, flexShrink: 0 }}>
                <div style={{ width: 10, height: 10, borderRadius: '50%', background: a.color, boxShadow: `0 0 8px ${a.color}88`, marginTop: 3, flexShrink: 0 }} />
                {i < items.length-1 && <div style={{ width: 1, flex: 1, background: 'var(--bdr)', marginTop: 4, marginBottom: 0, minHeight: 14 }} />}
              </div>
              <div style={{ flex: 1, paddingBottom: i < items.length-1 ? 8 : 0 }}>
                <div style={{ fontSize: 13, color: 'var(--t1)', lineHeight: 1.4 }}>{a.text}</div>
                <div style={{ fontSize: 11, color: 'var(--t3)', marginTop: 2 }}>{a.time}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── Today Tasks ─────────────────────────────────────────────────
  function TodayTasks({ tasks, setTasks }) {
    const priorityColor = { high: '#EF4444', medium: '#F59E0B', low: '#22C55E' };
    const toggle = (id) => setTasks(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));
    return (
      <div className="glass-card" style={{ padding: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--t1)' }}>Zadania na dziś</div>
          <span style={{ fontSize: 11, background: 'rgba(124,92,255,.15)', color: '#7C5CFF', padding: '2px 8px', borderRadius: 99, fontWeight: 600 }}>
            {tasks.filter(t => !t.done).length} pozostało
          </span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {tasks.map(t => (
            <div key={t.id} onClick={() => toggle(t.id)} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px',
              borderRadius: 10, cursor: 'pointer', transition: 'background .15s',
              background: t.done ? 'rgba(255,255,255,0.02)' : 'var(--bg-hover)',
              opacity: t.done ? 0.55 : 1,
            }}
            onMouseEnter={e => e.currentTarget.style.background='var(--bg2)'}
            onMouseLeave={e => e.currentTarget.style.background=t.done?'rgba(255,255,255,0.02)':'var(--bg-hover)'}
            >
              <div style={{
                width: 16, height: 16, borderRadius: 5, flexShrink: 0,
                border: t.done ? 'none' : `1.5px solid ${priorityColor[t.priority]}`,
                background: t.done ? '#22C55E' : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all .15s',
              }}>
                {t.done && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>}
              </div>
              <span style={{ fontSize: 13, color: 'var(--t1)', flex: 1, textDecoration: t.done ? 'line-through' : 'none' }}>{t.text}</span>
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: priorityColor[t.priority], flexShrink: 0 }} />
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── Dashboard (main export) ─────────────────────────────────────
  window.Dashboard = function Dashboard({ todayTasks, setTodayTasks, kanbanLeads }) {
    const S = window.SEED;
    const leads = kanbanLeads || S.kanbanLeads;

    // Derive KPIs from the sales funnel (Kanban) data
    const totalLeads   = leads.length;
    const wonLeads     = leads.filter(l => l.column === 'won');
    const lostLeads    = leads.filter(l => l.column === 'lost');
    const pipelineLeads= leads.filter(l => l.column !== 'won' && l.column !== 'lost');
    const pipelineValue= pipelineLeads.reduce((s,l) => s + l.value, 0);
    const revenue      = wonLeads.reduce((s,l) => s + l.value, 0);
    const decided      = wonLeads.length + lostLeads.length;
    const conversion   = decided > 0 ? (wonLeads.length / decided) * 100 : 0;
    const goalTarget   = S.monthlyGoalTarget || 1000000;
    const goalProgress = Math.min(100, Math.round((revenue / goalTarget) * 100));

    const kpis = S.kpis.map(k => {
      if (k.id === 'leads')      return { ...k, value: totalLeads };
      if (k.id === 'pipeline')   return { ...k, value: pipelineValue };
      if (k.id === 'conversion') return { ...k, value: conversion };
      if (k.id === 'revenue')    return { ...k, value: revenue };
      return k;
    });

    // Leads by source, derived from live Kanban data
    const sourceColors = { 'Google':'#7C5CFF', 'Polecenia':'#4DA3FF', 'Social':'#00D9FF', 'Formularz':'#22C55E' };
    const bySourceCount = {};
    leads.forEach(l => { bySourceCount[l.source] = (bySourceCount[l.source]||0) + 1; });
    const leadsBySource = Object.entries(bySourceCount).map(([name, count]) => ({
      name: name === 'Google' ? 'Google Ads' : name === 'Social' ? 'Meta Ads' : name,
      value: totalLeads > 0 ? Math.round((count / totalLeads) * 100) : 0,
      color: sourceColors[name] || '#7C5CFF',
    })).sort((a,b) => b.value - a.value);

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        {/* KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16 }}>
          {kpis.map(k => <KPICard key={k.id} kpi={k} />)}
        </div>

        {/* Charts row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16 }}>
          <SalesChart data={S.salesData} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <DonutChart data={leadsBySource} />
            <GoalGauge value={goalProgress} />
          </div>
        </div>

        {/* Bottom row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <ActivityFeed items={S.recentActivity} />
          <TodayTasks tasks={todayTasks} setTasks={setTodayTasks} />
        </div>
      </div>
    );
  };
})();
