// AI Intelligence — flagship cross-event marketing & pricing intelligence
const Intelligence = ({ setRoute }) => {
  const [tab, setTab] = React.useState('audiences');

  // ── Smart audiences (lookalike + cross-event)
  const audiences = [
    {
      id: 'la1',
      name: 'Lookalike of Apparat top buyers',
      basis: 'Audio embedding + venue history + price band',
      reach: 12420,
      predicted: 1840,
      lift: '+24%',
      confidence: 'high',
      tags: ['lookalike', 'electronic', 'Berlin'],
    },
    {
      id: 'cr1',
      name: 'Punjabi concert buyers · DACH',
      basis: 'Bought any Punjabi concert in last 18mo across all organisers',
      reach: 8240,
      predicted: 1240,
      lift: '+18%',
      confidence: 'high',
      tags: ['cross-event', 'Punjabi', 'opt-in WA'],
    },
    {
      id: 'rt1',
      name: 'Karan Aujla page · clicked, didn\'t buy',
      basis: 'Visited event page 2+ times in last 14d, no purchase',
      reach: 2840,
      predicted: 680,
      lift: '+34%',
      confidence: 'very high',
      tags: ['retargeting', 'high-intent'],
    },
    {
      id: 'cs1',
      name: 'Sufi-night attendees · likely Garba interest',
      basis: 'Cross-genre embedding similarity',
      reach: 4120,
      predicted: 380,
      lift: '+9%',
      confidence: 'medium',
      tags: ['cross-genre', 'discovery'],
    },
  ];

  // ── Pricing & demand recs
  const pricingRecs = [
    {
      event: 'Apparat · Berghain',
      date: '24. Mai',
      tier: 'GA',
      current: 42,
      recommended: 45,
      delta: '+€2,140',
      sellThrough: 0.94,
      reasoning: 'Sold 78% in first week vs 62% comparable. Demand exceeding supply curve.',
      confidence: 0.94,
    },
    {
      event: 'Hot Chip · Astra',
      date: '12. Jun',
      tier: 'Early Bird',
      current: 28,
      recommended: 26,
      delta: '+€840',
      sellThrough: 0.41,
      reasoning: 'Velocity 38% below benchmark. Lower price → projected sell-out 12 days earlier.',
      confidence: 0.81,
    },
    {
      event: 'Tempelhof Open Air',
      date: '28. Jul',
      tier: 'VIP',
      current: 180,
      recommended: 195,
      delta: '+€1,320',
      sellThrough: 0.88,
      reasoning: 'VIP tier underpriced vs Roosevelt VIP (€210). Demographic match.',
      confidence: 0.78,
    },
  ];

  // ── Demand forecast
  const forecast = [
    { d: 'Mon', actual: 42, predicted: 48 },
    { d: 'Tue', actual: 55, predicted: 52 },
    { d: 'Wed', actual: 68, predicted: 70 },
    { d: 'Thu', actual: 78, predicted: 82 },
    { d: 'Fri', actual: 92, predicted: 95 },
    { d: 'Sat', actual: null, predicted: 108 },
    { d: 'Sun', actual: null, predicted: 88 },
  ];

  // ── Anomalies & insights
  const anomalies = [
    { tone: 'warning', icon: 'warning', title: 'Hot Chip clicks dropped 41% vs forecast', detail: 'Likely cause: Instagram ad paused 2 days ago. Resume ad or rebalance to WhatsApp.', action: 'Restart IG ad', when: '2h ago' },
    { tone: 'success', icon: 'sparkle', title: 'Apparat WhatsApp open rate hit 96%', detail: '4.2% above your 30-day average. The "Einlass reminder" template is performing exceptionally.', action: 'Reuse template', when: '6h ago' },
    { tone: 'accent', icon: 'users', title: '1,240 new opt-ins this week', detail: 'Punjabi-pop checkout flow opt-in rate jumped from 64% → 78% after the consent rewrite.', action: 'View segment', when: 'yesterday' },
    { tone: 'warning', icon: 'cash', title: 'Refund rate on Roosevelt up 2.4x', detail: '12 refunds in 24h vs baseline 5/week. Most cite venue accessibility — review listing.', action: 'Open event', when: 'yesterday' },
  ];

  return (
    <div style={{ padding: '24px 36px 60px', maxWidth: 1400, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', marginBottom: 22 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <div style={{
              width: 22, height: 22, borderRadius: 6,
              background: 'linear-gradient(135deg, var(--accent), var(--indigo))',
              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name="sparkle" size={12}/></div>
            <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--accent-ink)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Intelligence</span>
            <Chip tone="accent" size="sm">Beta</Chip>
          </div>
          <h1 className="display" style={{ margin: 0, fontSize: 30, fontWeight: 500, letterSpacing: '-0.02em' }}>AI for your events</h1>
          <div style={{ fontSize: 13.5, color: 'var(--ink-3)', marginTop: 4 }}>Cross-event audiences, pricing recommendations, demand forecasts, and anomaly alerts.</div>
        </div>
        <div style={{ flex: 1 }}/>
        <Button variant="secondary" icon="settings">Models & data sources</Button>
      </div>

      {/* Value summary */}
      <Card pad={0} style={{ marginBottom: 18, overflow: 'hidden' }}>
        <div style={{ padding: 22, background: 'linear-gradient(135deg, oklch(0.22 0.05 280) 0%, oklch(0.18 0.06 320) 100%)', color: '#fff', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 90% -30%, oklch(0.7 0.2 320), transparent 50%)', opacity: 0.4 }}/>
          <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
            <div>
              <div style={{ fontSize: 10.5, fontWeight: 600, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Estimated value · April</div>
              <div className="display" style={{ fontSize: 36, fontWeight: 500, marginTop: 4, letterSpacing: '-0.02em' }}>+18.4k €</div>
              <div style={{ fontSize: 11.5, opacity: 0.75, marginTop: 2 }}>From AI recommendations applied</div>
            </div>
            <div style={{ borderLeft: '1px solid rgba(255,255,255,0.15)', paddingLeft: 24 }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Smart audiences</div>
              <div className="display" style={{ fontSize: 28, fontWeight: 500, marginTop: 4 }}>27.6k</div>
              <div style={{ fontSize: 11.5, opacity: 0.75, marginTop: 2 }}>Targetable across 14 segments</div>
            </div>
            <div style={{ borderLeft: '1px solid rgba(255,255,255,0.15)', paddingLeft: 24 }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Pricing recs</div>
              <div className="display" style={{ fontSize: 28, fontWeight: 500, marginTop: 4 }}>9 active</div>
              <div style={{ fontSize: 11.5, opacity: 0.75, marginTop: 2 }}>+4.3k € projected uplift</div>
            </div>
            <div style={{ borderLeft: '1px solid rgba(255,255,255,0.15)', paddingLeft: 24 }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Alerts</div>
              <div className="display" style={{ fontSize: 28, fontWeight: 500, marginTop: 4 }}>4 new</div>
              <div style={{ fontSize: 11.5, opacity: 0.75, marginTop: 2 }}>2 actionable in next 24h</div>
            </div>
          </div>
        </div>
      </Card>

      <Tabs value={tab} onChange={setTab} options={[
        { value: 'audiences', label: 'Smart audiences', count: audiences.length },
        { value: 'pricing', label: 'Pricing & demand', count: pricingRecs.length },
        { value: 'anomalies', label: 'Insights & alerts', count: anomalies.length },
        { value: 'lookalike', label: 'Lookalike builder' },
      ]}/>

      {tab === 'audiences' && (
        <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          {audiences.map(a => (
            <Card key={a.id}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                    <Icon name="sparkle" size={11} style={{ color: 'var(--accent)' }}/>
                    <span style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--accent-ink)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>AI segment</span>
                    {a.confidence === 'very high' && <Chip tone="success" size="sm">{a.confidence}</Chip>}
                    {a.confidence === 'high' && <Chip tone="accent" size="sm">{a.confidence}</Chip>}
                    {a.confidence === 'medium' && <Chip tone="neutral" size="sm">{a.confidence}</Chip>}
                  </div>
                  <div style={{ fontSize: 14.5, fontWeight: 600 }}>{a.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4, lineHeight: 1.5 }}>{a.basis}</div>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 14, padding: 12, background: 'var(--bg-sunken)', borderRadius: 10 }}>
                <div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Reach</div>
                  <div className="mono" style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>{a.reach.toLocaleString()}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Predicted buyers</div>
                  <div className="mono" style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>{a.predicted.toLocaleString()}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Lift vs broad</div>
                  <div className="mono" style={{ fontSize: 16, fontWeight: 600, color: 'var(--success)', marginTop: 2 }}>{a.lift}</div>
                </div>
              </div>

              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 12 }}>
                {a.tags.map(t => <Chip key={t} tone="neutral" size="sm">{t}</Chip>)}
              </div>

              <div style={{ display: 'flex', gap: 6, marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
                <Button variant="primary" size="sm" icon="send" onClick={() => setRoute('messages-whatsapp')}>Broadcast WhatsApp</Button>
                <Button variant="secondary" size="sm" icon="mail" onClick={() => setRoute('messages-email')}>Email</Button>
                <div style={{ flex: 1 }}/>
                <Button variant="ghost" size="sm" icon="more"/>
              </div>
            </Card>
          ))}
        </div>
      )}

      {tab === 'pricing' && (
        <div style={{ marginTop: 16 }}>
          {/* Forecast chart card */}
          <Card style={{ marginBottom: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>Demand forecast · next 7 days</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>Projected daily ticket volume across all active events</div>
              </div>
              <div style={{ display: 'flex', gap: 14, fontSize: 11.5, color: 'var(--ink-3)' }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: 'var(--ink)' }}/>Actual</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: 'var(--accent)', opacity: 0.6 }}/>Predicted</span>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 18, height: 160 }}>
              {forecast.map(b => (
                <div key={b.d} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, width: '100%', height: 130 }}>
                    {b.actual != null && <div style={{ flex: 1, height: `${b.actual}%`, background: 'var(--ink)', borderRadius: '4px 4px 0 0' }}/>}
                    <div style={{ flex: 1, height: `${b.predicted}%`, background: 'var(--accent)', opacity: b.actual == null ? 0.85 : 0.4, borderRadius: '4px 4px 0 0', border: b.actual == null ? '1px dashed var(--accent)' : 'none' }}/>
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 500 }}>{b.d}</div>
                </div>
              ))}
            </div>
          </Card>

          {/* Recommendations list */}
          <Card pad={0}>
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center' }}>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>Pricing recommendations</div>
              <Chip tone="accent" size="sm" style={{ marginLeft: 10 }}>{pricingRecs.length} active</Chip>
              <div style={{ flex: 1 }}/>
              <Button variant="ghost" size="sm" icon="settings">Recommendation rules</Button>
            </div>
            {pricingRecs.map((r, i) => (
              <div key={i} style={{ padding: '16px 18px', borderBottom: i < pricingRecs.length - 1 ? '1px solid var(--line)' : 'none', display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr auto', gap: 16, alignItems: 'center' }}>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                    <span style={{ fontSize: 13.5, fontWeight: 600 }}>{r.event}</span>
                    <Chip tone="neutral" size="sm">{r.tier}</Chip>
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>{r.reasoning}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Suggestion</div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 3 }}>
                    <span className="mono" style={{ fontSize: 13, color: 'var(--ink-3)', textDecoration: 'line-through' }}>{r.current} €</span>
                    <Icon name="arrow" size={11} style={{ color: 'var(--ink-3)' }}/>
                    <span className="mono" style={{ fontSize: 16, fontWeight: 700, color: r.recommended > r.current ? 'var(--success)' : 'var(--accent)' }}>{r.recommended} €</span>
                  </div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--success)', marginTop: 2, fontWeight: 600 }}>{r.delta} projected</div>
                </div>
                <div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600, marginBottom: 5 }}>Confidence</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ flex: 1, height: 5, borderRadius: 99, background: 'var(--bg-muted)', overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${r.confidence * 100}%`, background: r.confidence > 0.85 ? 'var(--success)' : 'var(--warning)' }}/>
                    </div>
                    <span className="mono" style={{ fontSize: 11.5, fontWeight: 600 }}>{Math.round(r.confidence * 100)}%</span>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <Button variant="primary" size="sm" icon="check">Apply</Button>
                  <Button variant="ghost" size="sm" icon="x"/>
                </div>
              </div>
            ))}
          </Card>
        </div>
      )}

      {tab === 'anomalies' && (
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {anomalies.map((a, i) => {
            const palette = a.tone === 'warning'
              ? { bg: 'oklch(0.97 0.04 75)', border: 'oklch(0.85 0.08 75)', icon: 'var(--warning)' }
              : a.tone === 'success'
              ? { bg: 'oklch(0.97 0.05 150)', border: 'oklch(0.85 0.08 150)', icon: 'var(--success)' }
              : { bg: 'var(--accent-soft)', border: 'oklch(0.85 0.06 30)', icon: 'var(--accent)' };
            return (
              <Card key={i} pad={16} style={{ background: palette.bg, borderColor: palette.border }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                  <div style={{ width: 32, height: 32, borderRadius: 9, background: 'var(--bg)', color: palette.icon, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, border: `1px solid ${palette.border}` }}>
                    <Icon name={a.icon} size={15}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                      <span style={{ fontSize: 13.5, fontWeight: 600 }}>{a.title}</span>
                      <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>· {a.when}</span>
                    </div>
                    <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>{a.detail}</div>
                  </div>
                  <Button variant="secondary" size="sm" icon="arrow">{a.action}</Button>
                </div>
              </Card>
            );
          })}
        </div>
      )}

      {tab === 'lookalike' && (
        <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 320px', gap: 14 }}>
          <Card>
            <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 4 }}>Find audiences like…</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 16 }}>Pick a seed event or buyer cohort. AI finds people across all organisers with similar taste, city, and price band.</div>

            <Field label="Seed event">
              <Select value="apparat" options={[
                { value: 'apparat', label: 'Apparat · Berghain · 24. Mai' },
                { value: 'hotchip', label: 'Hot Chip · Astra · 12. Jun' },
                { value: 'tempelhof', label: 'Tempelhof Open Air · 28. Jul' },
                { value: 'roosevelt', label: 'Roosevelt · Columbiahalle · 08. Jul' },
              ]}/>
            </Field>

            <Field label="Cohort to model" style={{ marginTop: 14 }}>
              <Select value="top" options={[
                { value: 'top', label: 'Top 1,000 buyers (highest LTV)' },
                { value: 'all', label: 'All ticket buyers' },
                { value: 'vip', label: 'VIP/Premium tier buyers only' },
                { value: 'repeat', label: 'Repeat buyers (2+ events)' },
              ]}/>
            </Field>

            <Field label="Constraints" style={{ marginTop: 14 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[
                  { l: 'Same city as seed', s: 'Berlin · Hamburg · Munich', on: true },
                  { l: 'Opted-in to WhatsApp', s: 'Required for WA broadcasts', on: true },
                  { l: 'Bought in last 18 months', s: 'Recency filter', on: true },
                  { l: 'Exclude existing buyers of this event', s: 'No double-targeting', on: true },
                  { l: 'Cross-organiser data', s: 'Other organisers in same genre', on: true },
                ].map((c, i, arr) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--line)' : 'none' }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 500 }}>{c.l}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c.s}</div>
                    </div>
                    <Toggle checked={c.on} onChange={()=>{}}/>
                  </div>
                ))}
              </div>
            </Field>

            <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
              <Button variant="primary" size="md" icon="sparkle">Generate audience</Button>
              <Button variant="secondary" size="md" icon="copy">Save as template</Button>
            </div>
          </Card>

          <Card style={{ background: 'var(--bg-sunken)' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>Live preview</div>
            <div className="display" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.02em' }}>12,420</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>matched people</div>
            <Divider style={{ margin: '14px 0' }}/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>Predicted CTR</span>
                <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>14.2%</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>Predicted buyers</span>
                <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>1,840</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>Projected revenue</span>
                <span className="mono" style={{ fontSize: 12, fontWeight: 600, color: 'var(--success)' }}>+€68,400</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>Lift vs broad targeting</span>
                <span className="mono" style={{ fontSize: 12, fontWeight: 600, color: 'var(--success)' }}>+24%</span>
              </div>
            </div>
            <Divider style={{ margin: '14px 0' }}/>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.5 }}>
              <strong style={{ color: 'var(--ink-2)' }}>Privacy:</strong> Cross-organiser modelling uses anonymised cohort embeddings — no individual purchase data is shared between organisers.
            </div>
          </Card>
        </div>
      )}
    </div>
  );
};

window.Intelligence = Intelligence;
