/* global React, Icon, Reveal, useInView, useCountUp, fmt, AnimatedLineChart, AnimatedBarChart, AreaLineChart */
const { useEffect, useRef, useState } = React;

/* ============ FEATURE BENTO ============ */
function FeatureBento() {
  return (
    <section id="features">
      <div className="section-inner">
        <Reveal className="section-head">
          <div className="section-eyebrow">ONE PLATFORM · EVERY TOOL</div>
          <h2 className="section-title">Everything marketing, <span className="gradient">finally together</span></h2>
          <p className="section-sub">Analytics, AI content, scheduling, budget — the whole stack under one login. No more tab graveyard, no more copy-pasting between six tools.</p>
        </Reveal>

        <Reveal className="bento reveal-stagger" stagger>
          <AiAgentCard/>
          <CalendarCard/>
          <UnifiedAnalyticsCard/>
          <BudgetCard/>
          <ChannelsCard/>
          <MarkAICard/>
        </Reveal>
      </div>
    </section>
  );
}

/* ---- AI Agents ---- */
function AiAgentCard() {
  return (
    <div className="bento-card ai-card span-3 tall">
      <span className="bento-tag" style={{ position: 'relative' }}>
        <Icon name="sparkle" size={12}/> AI AGENTS
      </span>
      <h3 className="bento-title" style={{ position: 'relative' }}>Captions, images &amp; strategy — generated on-brand.</h3>
      <p className="bento-desc" style={{ position: 'relative' }}>Two agents trained on your brand voice. Draft a week of posts, generate hero visuals, get weekly strategy briefs — all before your coffee cools.</p>
      <div className="ai-messages">
        <div className="ai-msg">
          <div className="avatar">✦</div>
          <div className="content">
            Give me 5 Instagram captions for our spring promo in <b>SPAR Latvia</b>'s voice.
          </div>
        </div>
        <div className="ai-msg" style={{ background: 'rgba(34,211,238,0.12)' }}>
          <div className="avatar" style={{ background: 'linear-gradient(135deg, #22D3EE, #2F7BFF)' }}>✧</div>
          <div className="content">
            <b>On it.</b> Drafting 5 captions + 2 hook variations · rendering 3 hero images at 1080×1350…
            <div style={{ marginTop: 6 }}>
              <span className="ai-typing"><span/><span/><span/></span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---- Calendar ---- */
function CalendarCard() {
  const [hoverDay, setHoverDay] = useState(14);
  const days = Array.from({ length: 35 }, (_, i) => {
    const d = i - 1;
    if (d < 1 || d > 30) return null;
    const posts = [];
    if ([3, 8, 14, 17, 22, 26].includes(d)) posts.push('ig');
    if ([5, 14, 20, 28].includes(d)) posts.push('fb');
    if ([7, 14, 21].includes(d)) posts.push('tt');
    if ([10, 24].includes(d)) posts.push('li');
    return { day: d, posts };
  });
  return (
    <div className="bento-card cal-card span-3 tall">
      <span className="bento-tag" style={{ background: 'rgba(236,72,153,0.08)', color: '#EC4899' }}>
        <Icon name="calendar" size={12}/> CONTENT CALENDAR
      </span>
      <h3 className="bento-title">Plan it, publish it — never leave the calendar.</h3>
      <p className="bento-desc">Schedule to Instagram, Facebook, TikTok, LinkedIn, X and YouTube from a single drag-and-drop view. Approvals, previews and auto-publish included.</p>
      <div className="cal-mini">
        {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => <div key={i} className="dow">{d}</div>)}
        {days.map((d, i) => {
          if (!d) return <div key={i} className="day empty"/>;
          const isToday = d.day === hoverDay;
          return (
            <div
              key={i}
              className={`day ${isToday ? 'today' : ''}`}
              onMouseEnter={() => setHoverDay(d.day)}
            >
              {d.day}
              {d.posts.length > 0 && (
                <div className="dot-row">
                  {d.posts.includes('ig') && <span className="p-ig"/>}
                  {d.posts.includes('fb') && <span className="p-fb"/>}
                  {d.posts.includes('tt') && <span className="p-tt"/>}
                  {d.posts.includes('li') && <span className="p-li"/>}
                </div>
              )}
            </div>
          );
        })}
      </div>
      <div className="cal-scheduled">
        <div className="post-img"/>
        <div className="text">
          <div className="t1">Spring promo · 3 platforms</div>
          <div className="t2">Auto-publishes Apr 22, 09:00 · IG · FB · TT</div>
        </div>
        <div className="cta">Preview</div>
      </div>
    </div>
  );
}

/* ---- Unified analytics ---- */
function UnifiedAnalyticsCard() {
  const [ref, inView] = useInView(0.1);
  const [reachRef, reachVal] = useCountUp(8541, { duration: 1600 });
  const [visitorsRef, visitorsVal] = useCountUp(856, { duration: 1400 });
  return (
    <div className="bento-card span-4 tall">
      <span className="bento-tag">
        <Icon name="chart" size={12}/> CROSS-CHANNEL
      </span>
      <h3 className="bento-title">Every channel, one number you can trust.</h3>
      <p className="bento-desc">Web, social, paid — blended into a single performance view. Filter by channel, campaign or date and export in two clicks.</p>

      <div ref={ref} style={{ marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div style={{ padding: 14, background: 'linear-gradient(135deg, rgba(108,92,231,0.08), rgba(47,123,255,0.04))', borderRadius: 12, border: '1px solid rgba(108,92,231,0.1)' }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>Total Reach</div>
          <div ref={reachRef} style={{ fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 800, color: 'var(--violet)', marginTop: 6, letterSpacing: '-0.02em' }}>{fmt(reachVal)}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>All channels combined</div>
        </div>
        <div style={{ padding: 14, background: 'linear-gradient(135deg, rgba(16,185,129,0.08), rgba(16,185,129,0.02))', borderRadius: 12, border: '1px solid rgba(16,185,129,0.12)' }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>Web Traffic</div>
          <div ref={visitorsRef} style={{ fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 800, color: 'var(--emerald)', marginTop: 6, letterSpacing: '-0.02em' }}>{fmt(visitorsVal)}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>GA4 · last 30 days</div>
        </div>
      </div>
      <div style={{ marginTop: 14 }}>
        <AreaLineChart width={600} height={140}/>
      </div>
      <div style={{ display: 'flex', gap: 14, justifyContent: 'center', fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>
        <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: '#EC4899', marginRight: 4 }}/>Followers</span>
        <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: '#10B981', marginRight: 4 }}/>Reach</span>
        <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: '#2F7BFF', marginRight: 4 }}/>Views</span>
      </div>
    </div>
  );
}

/* ---- Budget ---- */
function BudgetCard() {
  const [ref, inView] = useInView(0.1);
  return (
    <div className="bento-card span-2 tall">
      <span className="bento-tag" style={{ background: 'rgba(16,185,129,0.08)', color: 'var(--emerald)' }}>
        <Icon name="wallet" size={12}/> BUDGET
      </span>
      <h3 className="bento-title">Spend where it works.</h3>
      <p className="bento-desc">Track budget vs actual, set per-channel caps, and forecast ROAS from live campaign data.</p>
      <div ref={ref} style={{ marginTop: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4, fontSize: 12 }}>
          <span style={{ color: 'var(--muted)' }}>Planned</span>
          <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>€40,000</span>
        </div>
        <div style={{ height: 10, background: '#EDF0F7', borderRadius: 6, overflow: 'hidden', position: 'relative' }}>
          <div style={{ height: '100%', width: inView ? '83%' : 0, background: 'linear-gradient(90deg, var(--violet), var(--blue))', borderRadius: 6, transition: 'width 1.4s cubic-bezier(.2,.8,.2,1)' }}/>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 11 }}>
          <span style={{ color: 'var(--emerald)', fontWeight: 600 }}>€33,200 spent</span>
          <span style={{ color: 'var(--muted)' }}>€6,800 left</span>
        </div>

        <div style={{ marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {[
            { c: 'Google Ads', v: 32.26, color: '#2F7BFF' },
            { c: 'Facebook', v: 16.13, color: '#1877F2' },
            { c: 'Instagram', v: 16.13, color: '#EC4899' },
            { c: 'TikTok', v: 16.13, color: '#111' },
          ].map((c, i) => (
            <div key={c.c} style={{ padding: 10, background: '#F7F8FC', borderRadius: 10 }}>
              <div style={{ fontSize: 10, color: 'var(--muted)', fontWeight: 600 }}>{c.c}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 700, color: 'var(--ink)', marginTop: 3 }}>{c.v}%</div>
              <div style={{ height: 3, background: '#EDF0F7', borderRadius: 2, marginTop: 6, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: inView ? `${c.v * 2.5}%` : 0, background: c.color, transition: `width 1.4s ease ${0.2 + i * 0.1}s` }}/>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---- Channels (social icons) ---- */
function ChannelsCard() {
  const channels = [
    { n: 'Instagram', icon: 'instagram', bg: 'linear-gradient(135deg, #EC4899, #F59E0B)', reach: 8509 },
    { n: 'Facebook', icon: 'facebook', bg: '#1877F2', reach: 32 },
    { n: 'TikTok', icon: 'tiktok', bg: '#111', reach: 2150 },
    { n: 'LinkedIn', icon: 'linkedin', bg: '#0A66C2', reach: 440 },
    { n: 'X', icon: 'x', bg: '#111', reach: 180 },
    { n: 'YouTube', icon: 'youtube', bg: '#FF0000', reach: 1200 },
  ];
  return (
    <div className="bento-card span-3 short">
      <span className="bento-tag" style={{ background: 'rgba(47,123,255,0.08)', color: 'var(--blue)' }}>
        <Icon name="plug" size={12}/> INTEGRATIONS
      </span>
      <h3 className="bento-title">Every major platform, natively connected.</h3>
      <p className="bento-desc">Publish, pull analytics and manage ads across six networks — plus GA4, Meta Ads and Google Ads out of the box.</p>
      <div style={{ marginTop: 22, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
        {channels.map((c) => (
          <div key={c.n} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 10, background: '#F7F8FC', borderRadius: 10, transition: 'transform .3s, box-shadow .3s', cursor: 'pointer' }}
            onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 10px 20px -8px rgba(0,0,0,0.1)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = ''; }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: c.bg, color: '#fff', display: 'grid', placeItems: 'center' }}>
              <Icon name={c.icon} size={16}/>
            </div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink)' }}>{c.n}</div>
              <div style={{ fontSize: 10, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>{fmt(c.reach)} reach</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- MarkAI ---- */
function MarkAICard() {
  return (
    <div className="bento-card span-3 short" style={{ background: 'linear-gradient(135deg, #0B1033 0%, #1E2A78 100%)', color: '#fff', borderColor: 'transparent', overflow: 'hidden', position: 'relative' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 90% 10%, rgba(108,92,231,0.5), transparent 50%)' }}/>
      <span className="bento-tag" style={{ background: 'rgba(255,255,255,0.15)', color: '#fff', position: 'relative' }}>
        <Icon name="robot" size={12}/> MARKAI · YOUR MARKETING GURU
      </span>
      <h3 className="bento-title" style={{ color: '#fff', position: 'relative' }}>Insights, not dashboards.</h3>
      <p className="bento-desc" style={{ color: 'rgba(255,255,255,0.7)', position: 'relative' }}>MarkAI reads your data and tells you what to do next — in plain English.</p>
      <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 8, position: 'relative' }}>
        {[
          { icon: '⚠️', text: 'Instagram engagement 54.2% — unusually high. Industry avg is 1–5%.', c: '#FBBF24' },
          { icon: '💡', text: 'Instagram reach is 265.9× higher than Facebook — double down.', c: '#8B7BFF' },
          { icon: '✅', text: 'Bounce rate 42.8% — below industry avg. Web UX is working.', c: '#10B981' },
        ].map((m, i) => (
          <div key={i} style={{ display: 'flex', gap: 10, padding: '10px 12px', background: 'rgba(255,255,255,0.06)', border: `1px solid ${m.c}33`, borderRadius: 10, fontSize: 12, lineHeight: 1.45 }}>
            <span style={{ fontSize: 14 }}>{m.icon}</span>
            <span style={{ color: 'rgba(255,255,255,0.9)' }}>{m.text}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { FeatureBento });
