// scenes.jsx — WhiteSpace platform animation
// Story: chaos (scattered data) → convergence (hero) → constellation (features)

// ─── Data definitions ──────────────────────────────────────────────────────

const DATA_SOURCES = [
  { id: 'pos',     title: 'POS Systems',          sub: 'Direct API or daily email reports',        tags: ['Loyverse','Square','Toast','+11 more'], accent: 'oklch(72% 0.18 240)', icon: 'square' },
  { id: 'email',   title: 'Email Reports',        sub: 'Any POS format — CSV, PDF, HTML',           tags: ['Retail HQ','Blueprint','Any POS'],       accent: 'oklch(72% 0.20 310)', icon: 'mail' },
  { id: 'reviews', title: 'Guest Reviews',        sub: 'Sentiment analysis across platforms',       tags: ['Google','Facebook','TripAdvisor'],       accent: 'oklch(78% 0.18 85)',  icon: 'star' },
  { id: 'files',   title: 'Files & Spreadsheets', sub: 'The invoices and P&Ls sitting in your laptop', tags: ['Excel','CSV','PDF','Photos'],        accent: 'oklch(74% 0.16 150)', icon: 'doc' },
  { id: 'procure', title: 'Procurement & Invoices', sub: 'Supplier costs, delivery notes, price lists', tags: [],                                    accent: 'oklch(72% 0.14 210)', icon: 'box' },
  { id: 'menus',   title: 'Menus & Recipes',      sub: 'Menu photos, recipe costing, ingredient lists', tags: [],                                    accent: 'oklch(70% 0.20 20)',  icon: 'bars' },
];

const FEATURES = [
  { id: 'agents',    title: 'AI Agents',           sub: 'Ask anything — answers from your actual numbers, 24/7', accent: 'oklch(75% 0.22 50)',  icon: 'bolt' },
  { id: 'briefing',  title: 'Daily Briefing',      sub: 'Morning check-in with last night\u2019s performance', accent: 'oklch(82% 0.18 90)',  icon: 'sun' },
  { id: 'alerts',    title: 'Disruption Alerts',   sub: 'Real-time push when something breaks — LINE, email, WhatsApp', accent: 'oklch(70% 0.22 25)', icon: 'alert' },
  { id: 'reports',   title: 'Intelligence Reports',sub: 'Sales mix, procurement, guest sentiment — auto-generated', accent: 'oklch(75% 0.16 165)', icon: 'lines' },
  { id: 'line',      title: 'LINE Chat',           sub: 'Chat with your agents from your phone — no app needed', accent: 'oklch(72% 0.20 300)', icon: 'chat' },
  { id: 'stock',     title: 'Stock Intelligence',  sub: 'Waste alerts, reorder suggestions, cost variance', accent: 'oklch(74% 0.18 155)', icon: 'grid' },
  { id: 'growth',    title: 'Growth Agent',        sub: 'Proactive promotions — spots slow nights, creates occasions', accent: 'oklch(72% 0.22 30)',  icon: 'graph', badge: 'NEW' },
  { id: 'calendar',  title: 'Daily Calendar',      sub: 'Click any past day to review full performance', accent: 'oklch(72% 0.20 250)', icon: 'cal',   badge: 'NEW' },
];

// ─── Icon glyph (small, flat, on tinted square) ────────────────────────────

function Glyph({ type, color = '#fff', size = 22 }) {
  const s = size;
  const common = { width: s, height: s, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (type) {
    case 'square': return <svg {...common}><rect x="5" y="5" width="14" height="14" rx="2"/></svg>;
    case 'mail':   return <svg {...common}><rect x="4" y="6" width="16" height="12" rx="2"/><path d="M4 8l8 5 8-5"/></svg>;
    case 'star':   return <svg {...common}><path d="M12 4l2.5 5 5.5.8-4 3.9 1 5.5-5-2.7-5 2.7 1-5.5-4-3.9L9.5 9 12 4z"/></svg>;
    case 'doc':    return <svg {...common}><path d="M7 4h7l4 4v12H7z"/><path d="M14 4v4h4"/><path d="M9 13h6M9 16h4"/></svg>;
    case 'box':    return <svg {...common}><path d="M4 8l8-4 8 4-8 4-8-4z"/><path d="M4 8v8l8 4 8-4V8"/><path d="M12 12v8"/></svg>;
    case 'bars':   return <svg {...common}><path d="M5 6h14M5 12h14M5 18h14"/></svg>;
    case 'bolt':   return <svg {...common}><path d="M13 3L5 14h6l-1 7 8-11h-6l1-7z"/></svg>;
    case 'sun':    return <svg {...common}><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.5 5.5l1.4 1.4M17.1 17.1l1.4 1.4M5.5 18.5l1.4-1.4M17.1 6.9l1.4-1.4"/></svg>;
    case 'alert':  return <svg {...common}><path d="M12 4l10 17H2L12 4z"/><path d="M12 10v5M12 18v.5"/></svg>;
    case 'lines':  return <svg {...common}><path d="M4 7h16M4 12h16M4 17h10"/></svg>;
    case 'chat':   return <svg {...common}><path d="M4 5h16v11H9l-5 4V5z"/></svg>;
    case 'grid':   return <svg {...common}><rect x="4" y="4" width="6" height="6"/><rect x="14" y="4" width="6" height="6"/><rect x="4" y="14" width="6" height="6"/><rect x="14" y="14" width="6" height="6"/></svg>;
    case 'graph':  return <svg {...common}><path d="M4 18l5-6 4 3 7-9"/><path d="M15 6h5v5"/></svg>;
    case 'cal':    return <svg {...common}><rect x="4" y="6" width="16" height="14" rx="2"/><path d="M4 10h16M9 3v4M15 3v4"/></svg>;
    default: return <svg {...common}><circle cx="12" cy="12" r="6"/></svg>;
  }
}

// ─── Card (shared chrome for source + feature) ─────────────────────────────

function Card({ data, width = 340, compact = false, dim = 0, glow = 0, badge }) {
  const pad = compact ? 14 : 18;
  return (
    <div style={{
      width,
      background: 'linear-gradient(180deg, rgba(28,28,32,0.95) 0%, rgba(18,18,22,0.95) 100%)',
      border: '1px solid rgba(255,255,255,0.08)',
      borderRadius: 14,
      padding: pad,
      display: 'flex',
      gap: 12,
      alignItems: 'flex-start',
      boxShadow: glow > 0
        ? `0 0 ${40 * glow}px ${-4}px ${data.accent.replace('oklch(', 'oklch(').replace(')', ` / ${0.55 * glow})`)}, 0 8px 24px rgba(0,0,0,0.4)`
        : '0 8px 24px rgba(0,0,0,0.3)',
      opacity: 1 - dim * 0.75,
      transition: 'box-shadow 200ms',
    }}>
      {/* Icon tile */}
      <div style={{
        width: 38, height: 38,
        borderRadius: 9,
        background: data.accent.replace(')', ' / 0.18)'),
        border: `1px solid ${data.accent.replace(')', ' / 0.35)')}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <Glyph type={data.icon} color={data.accent} size={20} />
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            color: '#f6f4ef',
            fontSize: 15,
            fontWeight: 600,
            letterSpacing: '-0.01em',
          }}>{data.title}</div>
          {badge && (
            <span style={{
              fontSize: 9,
              fontWeight: 700,
              letterSpacing: '0.08em',
              color: 'oklch(80% 0.18 230)',
              background: 'oklch(80% 0.18 230 / 0.15)',
              border: '1px solid oklch(80% 0.18 230 / 0.4)',
              padding: '2px 5px',
              borderRadius: 3,
            }}>{badge}</span>
          )}
        </div>
        <div style={{
          color: 'rgba(246,244,239,0.55)',
          fontSize: 12,
          marginTop: 3,
          lineHeight: 1.4,
        }}>{data.sub}</div>

        {!compact && data.tags && data.tags.length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 8 }}>
            {data.tags.map((t, i) => (
              <span key={i} style={{
                fontSize: 10,
                color: 'rgba(246,244,239,0.65)',
                background: 'rgba(255,255,255,0.04)',
                border: '1px solid rgba(255,255,255,0.08)',
                padding: '2px 7px',
                borderRadius: 10,
              }}>{t}</span>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Hero card (the WhiteSpace brain) ──────────────────────────────────────

function HeroCard({ scale = 1, statsProgress = 0, glow = 0 }) {
  const w = 260;
  const h = 200;
  const pos = Math.floor(14 * statsProgress);
  const agents = Math.floor(4 * statsProgress);
  const channels = Math.floor(4 * statsProgress);

  return (
    <div style={{
      width: w, height: h,
      background: 'linear-gradient(180deg, #18181c 0%, #0e0e12 100%)',
      border: '1px solid rgba(255,255,255,0.12)',
      borderRadius: 14,
      padding: 22,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      transform: `scale(${scale})`,
      transformOrigin: 'center',
      boxShadow: glow > 0
        ? `0 0 ${80 * glow}px -10px oklch(80% 0.14 240 / ${0.45 * glow}), 0 20px 60px rgba(0,0,0,0.6)`
        : '0 20px 60px rgba(0,0,0,0.6)',
    }}>
      <div style={{ textAlign: 'center', marginTop: 6 }}>
        <div style={{ fontSize: 26, color: '#f6f4ef', letterSpacing: '-0.02em', fontWeight: 500 }}>
          White<span style={{ fontFamily: '"Instrument Serif", Georgia, serif', fontStyle: 'italic', fontWeight: 400, color: 'oklch(75% 0.19 55)' }}>Space</span><span style={{ color: 'oklch(75% 0.19 55)' }}>.</span>
        </div>
        <div style={{
          fontSize: 9,
          color: 'rgba(246,244,239,0.5)',
          letterSpacing: '0.22em',
          marginTop: 6,
        }}>AI INTELLIGENCE<br/>PLATFORM</div>
      </div>

      <div style={{
        height: 1,
        background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.18), transparent)',
      }}/>

      <div style={{ display: 'flex', justifyContent: 'space-around' }}>
        {[
          { num: pos, lbl: 'POS' },
          { num: agents, lbl: 'AGENTS' },
          { num: channels, lbl: 'CHANNELS' },
        ].map((s, i) => (
          <div key={i} style={{ textAlign: 'center' }}>
            <div style={{
              fontSize: 26,
              color: '#f6f4ef',
              fontWeight: 500,
              fontVariantNumeric: 'tabular-nums',
              letterSpacing: '-0.02em',
            }}>{s.num}</div>
            <div style={{
              fontSize: 9,
              color: 'rgba(246,244,239,0.5)',
              letterSpacing: '0.16em',
              marginTop: 2,
            }}>{s.lbl}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Background grid that pulses ───────────────────────────────────────────

function GridBackground({ intensity = 1 }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      backgroundImage: `
        linear-gradient(rgba(255,255,255,${0.025 * intensity}) 1px, transparent 1px),
        linear-gradient(90deg, rgba(255,255,255,${0.025 * intensity}) 1px, transparent 1px)
      `,
      backgroundSize: '48px 48px',
      maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 75%)',
    }}/>
  );
}

// ─── Particle flow (convergence motion lines) ──────────────────────────────

function ParticleFlow({ progress, originX, originY, targetX, targetY, color, delay = 0, count = 6 }) {
  // progress: 0..1 from scene
  return (
    <>
      {Array.from({ length: count }).map((_, i) => {
        const t = (progress - delay - i * 0.08);
        if (t < 0 || t > 1) return null;
        const eased = Easing.easeInOutCubic(clamp(t, 0, 1));
        const x = originX + (targetX - originX) * eased;
        const y = originY + (targetY - originY) * eased;
        const opacity = t < 0.15 ? t / 0.15 : t > 0.8 ? (1 - t) / 0.2 : 1;
        return (
          <div key={i} style={{
            position: 'absolute',
            left: x, top: y,
            width: 4, height: 4,
            borderRadius: 4,
            background: color,
            boxShadow: `0 0 12px 2px ${color}`,
            opacity: opacity * 0.9,
            transform: 'translate(-50%, -50%)',
          }}/>
        );
      })}
    </>
  );
}

// ─── Connection lines between hero and cards ───────────────────────────────

function ConnectionLine({ x1, y1, x2, y2, color, progress = 1, thickness = 1 }) {
  // progress draws the line from origin to target
  const dx = x2 - x1, dy = y2 - y1;
  const len = Math.sqrt(dx * dx + dy * dy);
  const angle = Math.atan2(dy, dx) * 180 / Math.PI;
  return (
    <div style={{
      position: 'absolute',
      left: x1, top: y1,
      width: len * clamp(progress, 0, 1),
      height: thickness,
      background: `linear-gradient(90deg, ${color.replace(')', ' / 0)')}, ${color.replace(')', ' / 0.5)')}, ${color.replace(')', ' / 0)')})`,
      transform: `rotate(${angle}deg)`,
      transformOrigin: '0 50%',
      pointerEvents: 'none',
    }}/>
  );
}

// ─── Caption (editorial) ───────────────────────────────────────────────────

function Caption({ text, x, y, size = 44, align = 'center', color = '#f6f4ef', italic = false }) {
  const { localTime, duration } = useSprite();
  const entryDur = 0.5;
  const exitDur = 0.4;
  const exitStart = duration - exitDur;

  let opacity = 1, ty = 0, clip = 100;
  if (localTime < entryDur) {
    const t = Easing.easeOutCubic(clamp(localTime / entryDur, 0, 1));
    opacity = t;
    ty = (1 - t) * 14;
  } else if (localTime > exitStart) {
    const t = Easing.easeInCubic(clamp((localTime - exitStart) / exitDur, 0, 1));
    opacity = 1 - t;
    ty = -t * 8;
  }

  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      transform: `translate(${align === 'center' ? '-50%' : '0'}, ${ty}px)`,
      opacity,
      fontFamily: italic ? '"Instrument Serif", Georgia, serif' : 'Inter, system-ui, sans-serif',
      fontStyle: italic ? 'italic' : 'normal',
      fontWeight: italic ? 400 : 500,
      fontSize: size,
      color,
      letterSpacing: '-0.02em',
      textAlign: align,
      lineHeight: 1.05,
      whiteSpace: 'pre',
    }}>
      {text}
    </div>
  );
}

Object.assign(window, {
  DATA_SOURCES, FEATURES, Card, HeroCard, GridBackground, ParticleFlow, ConnectionLine, Caption, Glyph,
});
