// v-insights.jsx — Customer Insights: aggregated, anonymised demand across
// Milton Keynes. New/repeat/dormant mix, value bands, reorder & basket
// behaviour, cuisine affinity vs your menu, and an order-time heatmap.

// ─── Segmented donut ─────────────────────────────────────────────────
function SegmentDonut({ segments, size=132, stroke=18, children }) {
  const r = (size-stroke)/2, c = 2*Math.PI*r;
  let acc = 0;
  return (
    <div style={{ position:'relative', width:size, height:size }}>
      <svg width={size} height={size} style={{ transform:'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(27,18,13,0.06)" strokeWidth={stroke}/>
        {segments.map((s,i)=>{
          const len = (s.pct/100)*c;
          const el = <circle key={i} cx={size/2} cy={size/2} r={r} fill="none" stroke={s.color} strokeWidth={stroke}
            strokeDasharray={`${len} ${c-len}`} strokeDashoffset={-acc} style={{ transition:'stroke-dashoffset 600ms var(--ease-out)' }}/>;
          acc += len;
          return el;
        })}
      </svg>
      {children && <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center' }}>{children}</div>}
    </div>
  );
}

function CIKpi({ icon, value, label, sub, delta, dir }) {
  const Icon = I[icon] || I.users;
  const c = dir==='up' ? '#247a41' : dir==='down' ? '#b0341a' : '#7C675B';
  return (
    <Card pad={16} hover>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <div style={{ width:34, height:34, borderRadius:10, background:'var(--bg-warm)', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon c="var(--brand-orange)" s={18}/></div>
        {delta && <span style={{ display:'inline-flex', alignItems:'center', gap:3, fontFamily:'var(--font-display)', fontWeight:800, fontSize:11.5, color:c }}>
          {dir==='up'&&<I.trendUp c={c} s={14}/>}{dir==='down'&&<I.trendDown c={c} s={14}/>}{delta}</span>}
      </div>
      <div style={{ marginTop:13, fontFamily:'var(--font-display)', fontWeight:900, fontSize:26, letterSpacing:'-0.02em', color:'var(--fg-primary)', lineHeight:1 }}>{value}</div>
      <div style={{ marginTop:6, fontFamily:'var(--font-display)', fontWeight:700, fontSize:12.5, color:'var(--fg-primary)' }}>{label}</div>
      <div style={{ marginTop:2, fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)' }}>{sub}</div>
    </Card>
  );
}

// generic distribution bar-chart card
function DistCard({ icon, title, data, note, accent='var(--brand-orange)' }) {
  const max = Math.max(...data.map(d=>d.pct));
  return (
    <Card>
      <Eyebrow style={{ marginBottom:16 }}>{icon} &nbsp;{title}</Eyebrow>
      <div style={{ display:'flex', alignItems:'flex-end', gap:10, height:118 }}>
        {data.map(d=>(
          <div key={d.b} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:6, height:'100%', justifyContent:'flex-end' }}>
            <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:12, color:'var(--fg-primary)' }}>{d.pct}%</span>
            <div style={{ width:'100%', maxWidth:42, height:`${d.pct/max*78}px`, background:accent, opacity:0.32+d.pct/max*0.55, borderRadius:'5px 5px 0 0', transition:'height 500ms var(--ease-out)' }}/>
            <span style={{ fontFamily:'var(--font-mono)', fontSize:9.5, color:'var(--warm-stone)', textAlign:'center' }}>{d.b}</span>
          </div>
        ))}
      </div>
      {note && <div style={{ marginTop:14, paddingTop:13, borderTop:'1px solid var(--soft-line)', fontFamily:'var(--font-body)', fontSize:12, color:'var(--warm-stone)', lineHeight:1.45 }}>{note}</div>}
    </Card>
  );
}

function InsightsScreen({ app }) {
  const repeat = CUST_MIX.find(m=>m.id==='repeat');
  const dormant = CUST_MIX.find(m=>m.id==='dormant');
  const newc = CUST_MIX.find(m=>m.id==='new');
  const heatMax = Math.max(...ORDER_HEAT.flatMap(r=>r.v));
  const heatColor = (v)=>{ const t=v/heatMax; return `rgba(216,90,20,${0.08+t*0.85})`; };
  const affMax = 100;

  return (
    <div>
      <PageHead eyebrow="Customer Insights" title="Who's ordering around you"
        sub="Aggregated, anonymised demand across Milton Keynes — never individual customers."
        right={<Segmented options={[{value:'today',label:'Today'},{value:'week',label:'7 days'},{value:'month',label:'30 days'}]} value={app.range} onChange={app.setRange}/>}/>

      {/* privacy banner */}
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 16px', background:'rgba(62,124,176,0.08)', border:'1px solid rgba(62,124,176,0.18)', borderRadius:12, marginBottom:16 }}>
        <I.lock c="#2f6694" s={16}/>
        <span style={{ fontFamily:'var(--font-body)', fontSize:12.5, color:'#2f6694' }}><strong style={{ fontFamily:'var(--font-display)' }}>Area-level only.</strong> Every figure is aggregated across estates — Lasso never shows individual addresses, names or contact details.</span>
      </div>

      {/* KPI row */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:16 }}>
        <CIKpi icon="users"   value={CUST_TOTAL.toLocaleString()} label="Reachable customers" sub="in your delivery radius" delta="+6%" dir="up"/>
        <CIKpi icon="refresh" value={`${repeat.pct}%`} label="Repeat rate" sub="2+ orders, last 30 days" delta="+5pt" dir="up"/>
        <CIKpi icon="tag"     value="£22.40" label="Avg basket" sub="per order" delta="+3%" dir="up"/>
        <CIKpi icon="clock"   value="9 days" label="Median reorder" sub="for repeat customers" delta="−1 day" dir="up"/>
      </div>

      {/* mix + value bands */}
      <div style={{ display:'grid', gridTemplateColumns:'1.25fr 1fr', gap:16, marginBottom:16 }}>
        <Card>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:16 }}>
            <Eyebrow><I.users c="var(--brand-orange)" s={13}/> &nbsp;New · repeat · dormant</Eyebrow>
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <span style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>Repeat rate · 8 wks</span>
              <Spark data={REPEAT_TREND} color="#2E8B4E" h={22} w={60} bars={false}/>
            </div>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:24 }}>
            <SegmentDonut segments={CUST_MIX.map(m=>({ pct:m.pct, color:m.color }))}>
              <div style={{ textAlign:'center' }}>
                <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:24, color:'var(--fg-primary)', lineHeight:1 }}>{repeat.pct}%</div>
                <div style={{ fontFamily:'var(--font-body)', fontSize:9.5, color:'var(--warm-stone)' }}>repeat</div>
              </div>
            </SegmentDonut>
            <div style={{ flex:1 }}>
              {CUST_MIX.map(m=>(
                <div key={m.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'9px 0', borderBottom:'1px solid var(--soft-line)' }}>
                  <span style={{ width:11, height:11, borderRadius:3, background:m.color, flexShrink:0 }}/>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13, color:'var(--fg-primary)' }}>{m.label}</div>
                    <div style={{ fontFamily:'var(--font-body)', fontSize:10.5, color:'var(--warm-stone)' }}>{m.note}</div>
                  </div>
                  <div style={{ textAlign:'right' }}>
                    <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:15, color:'var(--fg-primary)' }}>{m.pct}%</div>
                    <div style={{ fontFamily:'var(--font-body)', fontSize:10, color: m.delta.startsWith('+')?'#247a41':'#b0341a' }}>{m.delta} · {m.count.toLocaleString()}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card>
          <Eyebrow style={{ marginBottom:16 }}><I.crown c="var(--brand-orange)" s={13}/> &nbsp;Customer value bands</Eyebrow>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {VALUE_BANDS.map(b=>(
              <div key={b.band}>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:5 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                    <span style={{ width:9, height:9, borderRadius:3, background:b.color }}/>
                    <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:13, color:'var(--fg-primary)' }}>{b.band}</span>
                    <span style={{ fontFamily:'var(--font-body)', fontSize:11, color:'var(--warm-stone)' }}>{b.spend}</span>
                  </div>
                  <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:12.5, color:'var(--fg-primary)' }}>{b.count.toLocaleString()}</span>
                </div>
                <Bar pct={b.pct} color={b.color} h={8}/>
              </div>
            ))}
          </div>
          <div style={{ marginTop:15, paddingTop:13, borderTop:'1px solid var(--soft-line)', display:'flex', alignItems:'center', gap:8 }}>
            <I.zap c="var(--brand-orange)" s={14} f/>
            <span style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--warm-stone)' }}>Your top <strong style={{ color:'var(--fg-primary)', fontFamily:'var(--font-display)' }}>21%</strong> (VIP + Loyal) drive most repeat revenue.</span>
          </div>
        </Card>
      </div>

      {/* reorder + basket */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16 }}>
        <DistCard icon={<I.refresh c="var(--brand-orange)" s={13}/>} title="Reorder window" data={REORDER_WINDOW}
          note={<>Most repeat orders land <strong style={{ color:'var(--fg-primary)', fontFamily:'var(--font-display)' }}>4–14 days</strong> apart — time win-back nudges to day 10–12.</>}/>
        <DistCard icon={<I.tag c="var(--brand-orange)" s={13}/>} title="Basket size" data={BASKET_DIST} accent="#3E7CB0"
          note={<>The <strong style={{ color:'var(--fg-primary)', fontFamily:'var(--font-display)' }}>£18–25</strong> band is your sweet spot — bundles nudge baskets upward.</>}/>
      </div>

      {/* cuisine affinity + order heatmap */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1.2fr', gap:16, marginBottom:16 }}>
        <Card>
          <Eyebrow style={{ marginBottom:6 }}><I.pizza c="var(--brand-orange)" s={13}/> &nbsp;Cuisine demand vs your menu</Eyebrow>
          <div style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--warm-stone)', marginBottom:14 }}>What people near you crave — and the gaps you don't cover yet.</div>
          <div style={{ display:'flex', flexDirection:'column', gap:11 }}>
            {CUISINE_AFFINITY.map(a=>(
              <div key={a.name} style={{ display:'flex', alignItems:'center', gap:11 }}>
                <span style={{ width:90, fontFamily:'var(--font-display)', fontWeight:700, fontSize:12.5, color:'var(--fg-primary)', flexShrink:0 }}>{a.name}</span>
                <div style={{ flex:1 }}><Bar pct={a.demand/affMax*100} color={a.onMenu?'#2E8B4E':'#E0992A'} h={9}/></div>
                <span style={{ width:34, fontFamily:'var(--font-display)', fontWeight:800, fontSize:12, color:'var(--fg-primary)', textAlign:'right' }}>{a.demand}</span>
                {a.onMenu
                  ? <span style={{ width:78, fontFamily:'var(--font-body)', fontSize:10.5, color:'#247a41', display:'inline-flex', alignItems:'center', gap:3 }}><I.check c="#247a41" s={12}/>On menu</span>
                  : <span style={{ width:78, fontFamily:'var(--font-body)', fontSize:10.5, color:'#a86d12', display:'inline-flex', alignItems:'center', gap:3 }}><I.plus c="#a86d12" s={12}/>Gap</span>}
              </div>
            ))}
          </div>
          <div style={{ marginTop:14, display:'flex', alignItems:'center', gap:8, padding:'10px 12px', background:'rgba(224,153,42,0.10)', borderRadius:10 }}>
            <I.sparkle c="#a86d12" s={14} f/>
            <span style={{ fontFamily:'var(--font-body)', fontSize:11.5, color:'var(--horse-brown)' }}>High demand for <strong style={{ fontFamily:'var(--font-display)' }}>burgers &amp; desserts</strong> you don't yet serve — test a limited item.</span>
          </div>
        </Card>

        <Card>
          <Eyebrow style={{ marginBottom:16 }}><I.calendar c="var(--brand-orange)" s={13}/> &nbsp;When they order</Eyebrow>
          <div style={{ overflowX:'auto' }}>
            <div style={{ display:'grid', gridTemplateColumns:`46px repeat(${DAYPARTS.length},1fr)`, gap:5, minWidth:380 }}>
              <span/>
              {DAYPARTS.map(d=><span key={d} style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:9.5, color:'var(--warm-stone)', textAlign:'center', textTransform:'uppercase', letterSpacing:'0.04em' }}>{d}</span>)}
              {ORDER_HEAT.map(row=>(
                <React.Fragment key={row.day}>
                  <span style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:11, color:'var(--fg-primary)', display:'flex', alignItems:'center' }}>{row.day}</span>
                  {row.v.map((v,i)=>{
                    const t = v/heatMax;
                    return (
                      <div key={i} title={`${row.day} ${DAYPARTS[i]} · ${v} orders`} style={{ height:34, borderRadius:6, background:heatColor(v), display:'flex', alignItems:'center', justifyContent:'center', border:'1px solid rgba(27,18,13,0.04)' }}>
                        <span style={{ fontFamily:'var(--font-display)', fontWeight:800, fontSize:11, color: t>0.5?'#fff':'var(--horse-brown)' }}>{v}</span>
                      </div>
                    );
                  })}
                </React.Fragment>
              ))}
            </div>
          </div>
          <div style={{ marginTop:14, paddingTop:13, borderTop:'1px solid var(--soft-line)', display:'flex', alignItems:'center', gap:8 }}>
            <I.flame c="var(--brand-orange)" s={14} f/>
            <span style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--warm-stone)' }}>Demand peaks <strong style={{ color:'var(--fg-primary)', fontFamily:'var(--font-display)' }}>Fri–Sun evenings</strong> — protect kitchen capacity and target promos there.</span>
          </div>
        </Card>
      </div>

      {/* action strip */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
        <Card style={{ display:'flex', alignItems:'center', gap:16 }}>
          <div style={{ width:48, height:48, borderRadius:13, background:'rgba(193,59,31,0.12)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><I.refresh c="#C13B1F" s={22}/></div>
          <div style={{ flex:1 }}>
            <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:15, color:'var(--fg-primary)' }}>{dormant.count.toLocaleString()} dormant customers</div>
            <div style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--warm-stone)', marginTop:2 }}>No order in 30+ days. A win-back offer typically recovers 12–18%.</div>
          </div>
          <Btn kind="accent" size="sm" icon={<I.rocket c="#fff" s={15}/>} onClick={()=>app.openBuilder('wolverton')}>Win them back</Btn>
        </Card>
        <Card style={{ display:'flex', alignItems:'center', gap:16 }}>
          <div style={{ width:48, height:48, borderRadius:13, background:'rgba(62,124,176,0.13)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><I.gift c="#2f6694" s={22}/></div>
          <div style={{ flex:1 }}>
            <div style={{ fontFamily:'var(--font-display)', fontWeight:900, fontSize:15, color:'var(--fg-primary)' }}>{newc.count.toLocaleString()} new this month</div>
            <div style={{ fontFamily:'var(--font-body)', fontSize:12, color:'var(--warm-stone)', marginTop:2 }}>Convert first-timers into regulars with a second-order nudge.</div>
          </div>
          <Btn kind="white" size="sm" icon={<I.megaphone c="var(--fg-primary)" s={15}/>} onClick={()=>app.openBuilder('shenley')}>Set up welcome</Btn>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { InsightsScreen });
