// ---------- Analytics (live-updating charts on period change) ----------
const { LineChart, Line, BarChart, Bar, AreaChart, Area, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } = Recharts;

function Analytics() {
  const [period, setPeriod] = React.useState('30d');
  const [tick, setTick] = React.useState(0);
  React.useEffect(()=> { const h = () => setTick(x=>x+1); window.addEventListener('tweak-change', h); return ()=> window.removeEventListener('tweak-change', h); },[]);
  const colors = chartColors();

  const N = period === '7d' ? 7 : period === '30d' ? 30 : period === '3m' ? 90 : 365;
  const grain = period === '1y' ? 'M' : period === '3m' ? 'W' : 'D';

  const revenueData = React.useMemo(() => {
    const pts = Math.min(N, 30);
    return Array.from({length:pts}, (_,i) => {
      const x = i / pts;
      const base = period==='1y' ? 5200000 : period==='3m' ? 1800000 : period==='30d' ? 580000 : 130000;
      return {
        label: grain+String(i+1).padStart(2,'0'),
        revenue: Math.round(base + Math.sin((i+tick)*0.55) * base*0.2 + i*base*0.02),
        scoops:  Math.round(300 + Math.cos((i+tick)*0.45)*80 + i*4),
      };
    });
  }, [period, tick]);

  const flavorShare = React.useMemo(()=>{
    return FLAVORS.map((f,i) => ({
      name: f.name,
      value: 800 + Math.round(Math.sin(i*1.3+tick*0.3)*200) + i*60,
      color: f.color,
    }));
  }, [tick]);

  const prodVsSales = React.useMemo(() => {
    return FLAVORS.slice(0,6).map((f,i) => ({
      name: f.name.split(' ')[0],
      Produced: 120 + Math.round(Math.sin(i+tick*0.2)*30) + i*8,
      Sold: 110 + Math.round(Math.cos(i+tick*0.2)*25) + i*8,
    }));
  }, [tick]);

  const inventoryArea = React.useMemo(() => {
    return Array.from({length: 14}, (_,i) => ({
      day: 'D'+(i+1),
      Dairy: 280 + Math.sin(i*0.8+tick*0.1)*30 - i*4,
      Fruit: 120 + Math.cos(i*0.7+tick*0.1)*20 - i*3,
      Flavoring: 95 + Math.sin(i*0.4+tick*0.1)*15 - i*2,
    }));
  }, [tick]);

  const depositsData = DEPOSITS.slice().reverse().map(d => ({ date: d.deposit_date.slice(5), amount: d.amount_fcfa }));

  const totalRev = revenueData.reduce((s,x)=>s+x.revenue,0);
  const totalScoops = revenueData.reduce((s,x)=>s+x.scoops,0);
  const totalDeposits = DEPOSITS.reduce((s,x)=>s+x.amount_fcfa,0);
  const avgInv = Math.round(INVENTORY.reduce((s,i)=>s+i.quantity,0) / INVENTORY.length);
  const batches = (window.BATCHES || []).length;

  return (
    <div style={{display:'flex',flexDirection:'column',gap:24}}>
      {/* Period selector */}
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:12}}>
        <div style={{display:'flex',gap:4,padding:4,background:'var(--card)',border:'1px solid var(--border)',borderRadius:999}}>
          {[['7d','7 Days'],['30d','30 Days'],['3m','3 Months'],['1y','1 Year']].map(([v,l]) => (
            <button key={v} onClick={()=>setPeriod(v)} style={{
              padding:'8px 16px',borderRadius:999,fontSize:12,fontWeight:500,
              background: period===v ? 'var(--accent)' : 'transparent',
              color: period===v ? 'white' : 'var(--text-dim)',
              transition:'all .2s',
            }}>{l}</button>
          ))}
        </div>
        <div style={{display:'flex',gap:10}}>
          <button className="btn btn-ghost btn-sm"><Icon.Filter size={13}/> Filter</button>
          <button className="btn btn-primary btn-sm"><Icon.Download size={13}/> Export PDF</button>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:14}}>
        <MiniKpi label="Revenue" value={fmtFCFA(totalRev)} delta="+18.4%" color="var(--accent)"/>
        <MiniKpi label="Scoops sold" value={fmtNumber(totalScoops)} delta="+6.1%" color="var(--gold)"/>
        <MiniKpi label="Bank deposits" value={fmtFCFA(totalDeposits)} delta="+22.7%" color="var(--green)"/>
        <MiniKpi label="Avg inventory" value={avgInv+' u'} delta="-3.2%" color="var(--blue)"/>
        <MiniKpi label="Production batches" value={batches} delta="+9.0%" color="var(--purple)"/>
      </div>

      {/* Main chart */}
      <div className="card" style={{padding:22}}>
        <div style={{display:'flex',justifyContent:'space-between',marginBottom:18,flexWrap:'wrap',gap:10}}>
          <div>
            <h3 style={{fontSize:22,fontWeight:400}}>Revenue & Sales</h3>
            <div style={{fontSize:12,color:'var(--text-dim)'}}>Revenue in FCFA · Scoops sold per period</div>
          </div>
          <div style={{display:'flex',gap:14,fontSize:12,alignItems:'center'}}>
            <Legend2 color={colors.accent} label="Revenue"/>
            <Legend2 color={colors.gold} label="Scoops"/>
          </div>
        </div>
        <div style={{height:320}}>
          <ResponsiveContainer>
            <LineChart data={revenueData}>
              <defs>
                <linearGradient id="revGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={colors.accent} stopOpacity={0.35}/>
                  <stop offset="100%" stopColor={colors.accent} stopOpacity={0}/>
                </linearGradient>
              </defs>
              <CartesianGrid stroke={colors.border} strokeDasharray="3 3" vertical={false}/>
              <XAxis dataKey="label" stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false}/>
              <YAxis yAxisId="l" stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false} tickFormatter={v=>(v/1000).toFixed(0)+'k'}/>
              <YAxis yAxisId="r" orientation="right" stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false}/>
              <Tooltip content={<CustomTooltip fmt={v=>fmtNumber(v)}/>}/>
              <Line yAxisId="l" type="monotone" dataKey="revenue" stroke={colors.accent} strokeWidth={2.5} dot={false} activeDot={{r:5}}/>
              <Line yAxisId="r" type="monotone" dataKey="scoops"  stroke={colors.gold}   strokeWidth={2} dot={false} activeDot={{r:4}} strokeDasharray="4 4"/>
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* Dual chart row */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}} className="dash-row">
        <div className="card" style={{padding:22}}>
          <h3 style={{fontSize:18,fontWeight:400,marginBottom:6}}>Top flavors</h3>
          <div style={{fontSize:12,color:'var(--text-dim)',marginBottom:16}}>Share of scoops · current period</div>
          <div style={{height:260,position:'relative'}}>
            <ResponsiveContainer>
              <PieChart>
                <Pie data={flavorShare} dataKey="value" nameKey="name" innerRadius={60} outerRadius={95} paddingAngle={3} stroke="none">
                  {flavorShare.map((e,i) => <Cell key={i} fill={e.color}/>)}
                </Pie>
                <Tooltip content={<CustomTooltip fmt={fmtNumber}/>}/>
              </PieChart>
            </ResponsiveContainer>
            <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center',flexDirection:'column',pointerEvents:'none'}}>
              <div style={{fontSize:11,letterSpacing:'0.15em',textTransform:'uppercase',color:'var(--text-dim)',fontFamily:'JetBrains Mono'}}>Total</div>
              <div style={{fontFamily:'Cormorant Garamond',fontSize:26}}>{fmtNumber(flavorShare.reduce((s,x)=>s+x.value,0))}</div>
            </div>
          </div>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,marginTop:10}}>
            {flavorShare.slice(0,6).map(f => (
              <div key={f.name} style={{display:'flex',alignItems:'center',gap:8,fontSize:12}}>
                <span style={{width:8,height:8,borderRadius:2,background:f.color}}/>
                <span style={{color:'var(--text-dim)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{f.name}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="card" style={{padding:22}}>
          <h3 style={{fontSize:18,fontWeight:400,marginBottom:6}}>Production vs sales</h3>
          <div style={{fontSize:12,color:'var(--text-dim)',marginBottom:16}}>kg produced vs kg-equivalent sold</div>
          <div style={{height:300}}>
            <ResponsiveContainer>
              <BarChart data={prodVsSales}>
                <CartesianGrid stroke={colors.border} strokeDasharray="3 3" vertical={false}/>
                <XAxis dataKey="name" stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false}/>
                <YAxis stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false}/>
                <Tooltip content={<CustomTooltip/>} cursor={{fill:colors.border}}/>
                <Legend iconType="circle" wrapperStyle={{fontSize:12}}/>
                <Bar dataKey="Produced" fill={colors.accent} radius={[5,5,0,0]}/>
                <Bar dataKey="Sold" fill={colors.green} radius={[5,5,0,0]}/>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Inventory + Deposits */}
      <div style={{display:'grid',gridTemplateColumns:'1.4fr 1fr',gap:16}} className="dash-row">
        <div className="card" style={{padding:22}}>
          <h3 style={{fontSize:18,fontWeight:400,marginBottom:6}}>Inventory levels</h3>
          <div style={{fontSize:12,color:'var(--text-dim)',marginBottom:16}}>By category · last 14 days</div>
          <div style={{height:260}}>
            <ResponsiveContainer>
              <AreaChart data={inventoryArea}>
                <defs>
                  <linearGradient id="g1" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={colors.accent} stopOpacity={0.5}/><stop offset="100%" stopColor={colors.accent} stopOpacity={0}/></linearGradient>
                  <linearGradient id="g2" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={colors.gold} stopOpacity={0.5}/><stop offset="100%" stopColor={colors.gold} stopOpacity={0}/></linearGradient>
                  <linearGradient id="g3" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={colors.green} stopOpacity={0.5}/><stop offset="100%" stopColor={colors.green} stopOpacity={0}/></linearGradient>
                </defs>
                <CartesianGrid stroke={colors.border} strokeDasharray="3 3" vertical={false}/>
                <XAxis dataKey="day" stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false}/>
                <YAxis stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false}/>
                <Tooltip content={<CustomTooltip/>}/>
                <Legend iconType="circle" wrapperStyle={{fontSize:12}}/>
                <Area type="monotone" dataKey="Dairy" stroke={colors.accent} fill="url(#g1)" strokeWidth={2}/>
                <Area type="monotone" dataKey="Fruit" stroke={colors.gold}   fill="url(#g2)" strokeWidth={2}/>
                <Area type="monotone" dataKey="Flavoring" stroke={colors.green} fill="url(#g3)" strokeWidth={2}/>
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </div>
        <div className="card" style={{padding:22}}>
          <h3 style={{fontSize:18,fontWeight:400,marginBottom:6}}>Bank deposits</h3>
          <div style={{fontSize:12,color:'var(--text-dim)',marginBottom:16}}>FCFA · recent</div>
          <div style={{height:260}}>
            <ResponsiveContainer>
              <BarChart data={depositsData}>
                <CartesianGrid stroke={colors.border} strokeDasharray="3 3" vertical={false}/>
                <XAxis dataKey="date" stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false}/>
                <YAxis stroke={colors.textDim} fontSize={10} tickLine={false} axisLine={false} tickFormatter={v=>(v/1000000).toFixed(1)+'M'}/>
                <Tooltip content={<CustomTooltip fmt={fmtFCFA}/>} cursor={{fill:colors.border}}/>
                <Bar dataKey="amount" fill={colors.accent} radius={[6,6,0,0]}/>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>
    </div>
  );
}

function MiniKpi({ label, value, delta, color }) {
  const positive = !delta.startsWith('-');
  return (
    <div className="card" style={{padding:16,borderLeft:'3px solid '+color}}>
      <div style={{fontSize:10,letterSpacing:'0.15em',textTransform:'uppercase',color:'var(--text-dim)',fontFamily:'JetBrains Mono',marginBottom:6}}>{label}</div>
      <div style={{fontFamily:'Cormorant Garamond',fontSize:26,fontWeight:400,lineHeight:1}}>{value}</div>
      <div style={{fontSize:11,color: positive?'var(--green)':'var(--red)',marginTop:4}}>{delta}</div>
    </div>
  );
}
function Legend2({ color, label }) {
  return <div style={{display:'flex',alignItems:'center',gap:6,color:'var(--text-dim)'}}><span style={{width:10,height:10,borderRadius:2,background:color}}/>{label}</div>;
}

Object.assign(window, { Analytics });
