// Reports.jsx
(function () {

  function fmtVal(v) {
    if (v >= 1000000) return (v/1000000).toFixed(1).replace('.',',') + ' M zł';
    if (v >= 1000) return Math.round(v/1000) + ' k zł';
    return v + ' zł';
  }

  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,.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' }}>
            {unit === 'zł' ? fmtVal(p.value) : unit === '%' ? p.value + '%' : p.value}
          </div>
        ))}
      </div>
    );
  }

  function SectionCard({ title, subtitle, children, action }) {
    return (
      <div className="glass-card" style={{ padding:24 }}>
        <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', marginBottom:20 }}>
          <div>
            <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)' }}>{title}</div>
            {subtitle && <div style={{ fontSize:12, color:'var(--t3)', marginTop:2 }}>{subtitle}</div>}
          </div>
          {action}
        </div>
        {children}
      </div>
    );
  }

  window.Reports = function Reports() {
    const { BarChart, Bar, AreaChart, Area, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LabelList } = window.Recharts || {};
    const S = window.SEED;
    const months = S.salesData['12m'];
    const { useState } = React;
    const [periodMode, setPeriodMode] = useState('month'); // 'month' | 'range'
    const [monthIdx, setMonthIdx] = useState(months.length - 1);
    const [rangeFrom, setRangeFrom] = useState(0);
    const [rangeTo, setRangeTo] = useState(months.length - 1);

    const from = Math.min(rangeFrom, rangeTo);
    const to   = Math.max(rangeFrom, rangeTo);
    const chartData = periodMode === 'month' ? months.slice(Math.max(0, monthIdx - 1), monthIdx + 1) : months.slice(from, to + 1);
    const periodLabel = periodMode === 'month' ? months[monthIdx].date : `${months[from].date} – ${months[to].date}`;

    const handleExport = () => {
      const csv = [
        ['Miesiąc','Przychód','Poprzedni okres'],
        ...chartData.map(r => [r.date, r.value, r.prev])
      ].map(r => r.join(',')).join('\n');
      const blob = new Blob([csv], { type:'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url; a.download = 'raport_demo_crm.csv'; a.click();
      URL.revokeObjectURL(url);
    };

    return (
      <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
        {/* Header */}
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div>
            <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)' }}>Raporty sprzedaży</div>
            <div style={{ fontSize:12, color:'var(--t3)', marginTop:2 }}>Lipiec 2026 · dane mockowe</div>
          </div>
          <button onClick={handleExport} style={{
            padding:'8px 18px', borderRadius:10, border:'1px solid var(--bdr)',
            background:'var(--bg1)', color:'var(--t1)', fontWeight:600, fontSize:13,
            cursor:'pointer', display:'flex', alignItems:'center', gap:8, outline:'none',
            transition:'all .15s',
          }}
          onMouseEnter={e=>e.currentTarget.style.background='var(--bg2)'}
          onMouseLeave={e=>e.currentTarget.style.background='var(--bg1)'}
          >
            ⬇ Eksport CSV
          </button>
        </div>

        {/* Row 1: Bar + Area */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1.4fr', gap:20 }}>
          {/* Conversion by stage */}
          <SectionCard title="Konwersja wg etapu" subtitle="% leadów przechodzących dalej">
            <ResponsiveContainer width="100%" height={240}>
              <BarChart data={S.conversionByStage} layout="vertical" margin={{ top:0, right:30, left:0, bottom:0 }}>
                <defs>
                  <linearGradient id="barGrad" x1="0" y1="0" x2="1" y2="0">
                    <stop offset="0%"   stopColor="#7C5CFF" />
                    <stop offset="100%" stopColor="#4DA3FF" />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" horizontal={false} />
                <XAxis type="number" tick={{ fill:'var(--t3)', fontSize:11 }} axisLine={false} tickLine={false} domain={[0,100]} tickFormatter={v=>v+'%'} />
                <YAxis type="category" dataKey="stage" tick={{ fill:'var(--t2)', fontSize:12 }} axisLine={false} tickLine={false} width={80} />
                <Tooltip content={<GlassTooltip unit="%" />} cursor={{ fill:'rgba(124,92,255,.08)' }} />
                <Bar dataKey="rate" fill="url(#barGrad)" radius={[0,6,6,0]} maxBarSize={22}>
                  <LabelList dataKey="rate" position="right" style={{ fill:'var(--t2)', fontSize:11 }} formatter={v=>v+'%'} />
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </SectionCard>

          {/* Monthly revenue */}
          <SectionCard title="Przychód miesięczny" subtitle={periodMode==='month' ? `Miesiąc: ${periodLabel}` : `Zakres: ${periodLabel}`}
            action={
              <div style={{ display:'flex', gap:6, alignItems:'center', flexWrap:'wrap', justifyContent:'flex-end' }}>
                <div style={{ display:'flex', gap:4, background:'var(--bg1)', border:'1px solid var(--bdr)', borderRadius:9, padding:2 }}>
                  {[{v:'month',l:'Miesiąc'},{v:'range',l:'Zakres'}].map(o => (
                    <button key={o.v} onClick={()=>setPeriodMode(o.v)} style={{
                      padding:'5px 10px', borderRadius:7, border:'none', cursor:'pointer', fontSize:11.5,
                      fontWeight: periodMode===o.v?600:400,
                      background: periodMode===o.v?'rgba(124,92,255,.22)':'transparent',
                      color: periodMode===o.v?'#7C5CFF':'var(--t2)',
                    }}>{o.l}</button>
                  ))}
                </div>
                {periodMode==='month' ? (
                  <div style={{ width:110 }}><window.DemoSelect value={monthIdx} onChange={v=>setMonthIdx(Number(v))} options={months.map((m,i)=>({value:i,label:m.date}))} /></div>
                ) : (
                  <>
                    <div style={{ width:100 }}><window.DemoSelect value={rangeFrom} onChange={v=>setRangeFrom(Number(v))} options={months.map((m,i)=>({value:i,label:m.date}))} /></div>
                    <span style={{ fontSize:12, color:'var(--t3)' }}>–</span>
                    <div style={{ width:100 }}><window.DemoSelect value={rangeTo} onChange={v=>setRangeTo(Number(v))} options={months.map((m,i)=>({value:i,label:m.date}))} /></div>
                  </>
                )}
              </div>
            }
          >
            <ResponsiveContainer width="100%" height={240}>
              <AreaChart data={chartData} margin={{ top:4, right:4, left:0, bottom:0 }}>
                <defs>
                  <linearGradient id="repGrad1" 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="repGrad2" 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:10 }} axisLine={false} tickLine={false} interval={1} />
                <YAxis tick={{ fill:'var(--t3)', fontSize:10 }} axisLine={false} tickLine={false} tickFormatter={v=>v>=1000?v/1000+'k':v} width={38} />
                <Tooltip content={<GlassTooltip unit="zł" />} cursor={{ stroke:'rgba(124,92,255,.25)', strokeWidth:1 }} />
                <Area type="monotone" dataKey="prev"  stroke="#4DA3FF" fill="url(#repGrad2)" strokeWidth={1.5} dot={false} strokeDasharray="4 2" />
                <Area type="monotone" dataKey="value" stroke="#7C5CFF" fill="url(#repGrad1)" strokeWidth={2.5} dot={false} style={{ filter:'drop-shadow(0 0 5px rgba(124,92,255,.5))' }} />
              </AreaChart>
            </ResponsiveContainer>
          </SectionCard>
        </div>

        {/* Row 2: Donut + summary stats */}
        <div style={{ display:'grid', gridTemplateColumns:'320px 1fr', gap:20 }}>
          {/* Source donut */}
          <SectionCard title="Udział źródeł leadów" subtitle="Lipiec 2026">
            <ResponsiveContainer width="100%" height={180}>
              <PieChart>
                <Pie data={S.leadsBySource} innerRadius={52} outerRadius={78} paddingAngle={3} dataKey="value" strokeWidth={0} animationBegin={200}>
                  {S.leadsBySource.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:'grid', gridTemplateColumns:'1fr 1fr', gap:6, marginTop:8 }}>
              {S.leadsBySource.map((d,i) => (
                <div key={i} style={{ display:'flex', alignItems:'center', gap:7, fontSize:12 }}>
                  <div style={{ width:8, height:8, borderRadius:2, background:d.color, flexShrink:0 }} />
                  <span style={{ color:'var(--t2)' }}>{d.name}</span>
                  <span style={{ color:'var(--t1)', fontWeight:700, marginLeft:'auto' }}>{d.value}%</span>
                </div>
              ))}
            </div>
          </SectionCard>

          {/* Summary KPI grid */}
          <SectionCard title="Podsumowanie okresu" subtitle="Lipiec 2026">
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
              {[
                { label:'Łączny przychód',   val:'892 k zł',  sub:'↑ 15.8% r/r',    up:true,  color:'#22C55E' },
                { label:'Nowe kontrakty',     val:'14',        sub:'↑ 4 vs kwiecień', up:true,  color:'#7C5CFF' },
                { label:'Śr. wartość dealu',  val:'63.7 k zł', sub:'↑ 8.2%',         up:true,  color:'#4DA3FF' },
                { label:'Czas do zamknięcia', val:'18 dni',    sub:'↓ 3 dni',         up:true,  color:'#00D9FF' },
                { label:'Churn rate',         val:'2.1%',      sub:'↓ 0.4pp',        up:true,  color:'#22C55E' },
                { label:'NPS klientów',       val:'72',        sub:'↑ 5 pkt',        up:true,  color:'#F59E0B' },
              ].map((s,i) => (
                <div key={i} style={{ padding:'14px 16px', borderRadius:12, background:'var(--bg1)', border:'1px solid var(--bdr)' }}>
                  <div style={{ fontSize:11, color:'var(--t3)', marginBottom:4 }}>{s.label}</div>
                  <div style={{ fontSize:20, fontWeight:800, color:'var(--t1)', letterSpacing:-0.5 }}>{s.val}</div>
                  <div style={{ fontSize:11, color: s.up ? '#22C55E' : '#EF4444', marginTop:3, fontWeight:600 }}>{s.sub}</div>
                </div>
              ))}
            </div>
          </SectionCard>
        </div>
      </div>
    );
  };
})();
