// dashboard-tour.jsx — Auto-playing animated dashboard tour.
// A self-running mockup that cycles through scenes so visitors *see* the
// product working: new order arrives, AI generates description, loyalty
// member joins, revenue chart grows, campaign sends. Built to convert.

const DT_INK = '#1C1009';
const DT_AMBER = '#F97316';
const DT_AMBER_DEEP = '#C2410C';
const DT_AMBER_TINT = '#FFE4CC';
const DT_AMBER_SOFT = '#FFF1E4';
const DT_CREAM = '#FFFBF5';
const DT_PAPER = '#F3E4C8';
const DT_MUTED = '#5C4A3F';
const DT_DIM = '#7B6A5F';
const DT_BORDER = 'rgba(28,16,9,0.08)';
const DT_FOREST = '#16A34A';
const DT_BERRY = '#DB2777';
const DT_FN = '"Nunito", system-ui, sans-serif';
const DT_FB = '"DM Sans", system-ui, sans-serif';
const DT_FM = '"JetBrains Mono", ui-monospace, monospace';

const SCENES = [
  { id: 'orders',   label: 'New order, live',          duration: 5200 },
  { id: 'ai',       label: 'AI menu studio',           duration: 5400, soon: true },
  { id: 'loyalty',  label: 'Loyalty in action',        duration: 4800, soon: true },
  { id: 'revenue',  label: 'Sales analytics',           duration: 5000 },
  { id: 'campaign', label: 'Promotions in 3 taps',      duration: 5200, soon: true },
];

// ── Hook: typewriter ───────────────────────────────────────────────────────
function useTypewriter(text, active, speed = 22) {
  const [out, setOut] = React.useState('');
  React.useEffect(() => {
    if (!active) { setOut(''); return; }
    let i = 0;
    setOut('');
    const t = setInterval(() => {
      i++;
      setOut(text.slice(0, i));
      if (i >= text.length) clearInterval(t);
    }, speed);
    return () => clearInterval(t);
  }, [active, text, speed]);
  return out;
}

// ── Hook: animated number with easing ──────────────────────────────────────
function useAnimatedNumber(target, active, duration = 1400) {
  const [v, setV] = React.useState(0);
  React.useEffect(() => {
    if (!active) { setV(0); return; }
    let raf, start;
    const tick = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(eased * target);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [active, target, duration]);
  return v;
}

// ── The tour container ────────────────────────────────────────────────────
function DashboardTour() {
  const [sceneIdx, setSceneIdx] = React.useState(0);
  const [progress, setProgress] = React.useState(0);
  const [paused, setPaused] = React.useState(false);

  // Auto-advance with progress bar
  React.useEffect(() => {
    if (paused) return;
    const duration = SCENES[sceneIdx].duration;
    let raf, start;
    const tick = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      setProgress(p);
      if (p < 1) {
        raf = requestAnimationFrame(tick);
      } else {
        setSceneIdx((i) => (i + 1) % SCENES.length);
        setProgress(0);
      }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [sceneIdx, paused]);

  const goTo = (idx) => {
    setSceneIdx(idx);
    setProgress(0);
  };

  return (
    <div style={{
      background: DT_CREAM, borderRadius: 20,
      border: `1px solid ${DT_BORDER}`,
      boxShadow: '0 40px 100px rgba(28,16,9,0.18), 0 8px 24px rgba(28,16,9,0.06)',
      overflow: 'hidden', fontFamily: DT_FB, color: DT_INK,
    }}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      {/* ── Window chrome ─────────────────────────────────── */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '12px 16px', borderBottom: `1px solid ${DT_BORDER}`,
        background: 'rgba(28,16,9,0.02)',
      }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <span style={{ width: 11, height: 11, borderRadius: 99, background: '#FF5F57' }}/>
          <span style={{ width: 11, height: 11, borderRadius: 99, background: '#FEBC2E' }}/>
          <span style={{ width: 11, height: 11, borderRadius: 99, background: '#28C840' }}/>
        </div>
        <div style={{
          flex: 1, display: 'flex', justifyContent: 'center',
          fontFamily: DT_FM, fontSize: 11, color: DT_DIM,
        }}>
          <span style={{
            padding: '3px 12px', borderRadius: 6,
            background: 'rgba(28,16,9,0.04)',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 99, background: DT_FOREST }}/>
            app.robinrun.com / golden-karahi
          </span>
        </div>
        <span style={{
          fontFamily: DT_FM, fontSize: 10, color: DT_DIM,
          letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600,
        }}>Sample data</span>
      </div>

      {/* ── Scene area ────────────────────────────────────── */}
      <div style={{
        position: 'relative', minHeight: 520,
        background: DT_CREAM,
      }}>
        {SCENES.map((s, i) => (
          <div key={s.id} style={{
            position: 'absolute', inset: 0,
            opacity: i === sceneIdx ? 1 : 0,
            pointerEvents: i === sceneIdx ? 'auto' : 'none',
            transition: 'opacity .5s ease',
          }}>
            {s.id === 'orders'   && <SceneOrders   active={i === sceneIdx} progress={progress}/>}
            {s.id === 'ai'       && <SceneAI       active={i === sceneIdx} progress={progress}/>}
            {s.id === 'loyalty'  && <SceneLoyalty  active={i === sceneIdx} progress={progress}/>}
            {s.id === 'revenue'  && <SceneRevenue  active={i === sceneIdx} progress={progress}/>}
            {s.id === 'campaign' && <SceneCampaign active={i === sceneIdx} progress={progress}/>}
          </div>
        ))}
      </div>

      {/* ── Scene chips + progress ────────────────────────── */}
      <div style={{
        padding: '14px 20px',
        borderTop: `1px solid ${DT_BORDER}`,
        background: 'rgba(28,16,9,0.02)',
        display: 'flex', alignItems: 'center', gap: 8,
        flexWrap: 'wrap',
      }}>
        {SCENES.map((s, i) => {
          const active = i === sceneIdx;
          return (
            <button key={s.id} onClick={() => goTo(i)} style={{
              position: 'relative', overflow: 'hidden',
              padding: '7px 12px', borderRadius: 8, border: 0,
              background: active ? DT_INK : 'transparent',
              color: active ? DT_CREAM : DT_DIM,
              fontFamily: DT_FB, fontSize: 12, fontWeight: 600,
              cursor: 'pointer', transition: 'all .25s ease',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <span style={{
                width: 6, height: 6, borderRadius: 99,
                background: active ? DT_AMBER : 'rgba(28,16,9,0.2)',
              }}/>
              {s.label}
              {s.soon && (
                <span style={{
                  fontFamily: DT_FM, fontSize: 8.5, fontWeight: 700,
                  letterSpacing: '0.08em', textTransform: 'uppercase',
                  padding: '2px 5px', borderRadius: 5,
                  background: active ? 'rgba(255,251,245,0.16)' : 'rgba(28,16,9,0.07)',
                  color: active ? DT_CREAM : DT_DIM,
                }}>Soon</span>
              )}
              {active && (
                <span aria-hidden style={{
                  position: 'absolute', bottom: 0, left: 0,
                  height: 2, width: `${progress * 100}%`,
                  background: DT_AMBER, borderRadius: 99,
                  transition: 'width .08s linear',
                }}/>
              )}
            </button>
          );
        })}
        <div style={{ flex: 1 }}/>
        <span style={{
          fontFamily: DT_FM, fontSize: 10, color: DT_DIM,
          letterSpacing: '0.08em', textTransform: 'uppercase',
        }}>
          {paused ? 'Paused · hover to control' : 'Auto-tour'}
        </span>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 1 — Orders coming in live
// ═══════════════════════════════════════════════════════════════════════════
function SceneOrders({ active, progress }) {
  // Simulate a new order arriving at ~30% of the scene
  const newOrderVisible = active && progress > 0.20;
  const queueOpen = active && progress > 0.05;

  const baseRows = [
    { id: '#A2917', cust: 'Diego P.', items: '1× Smashburger · Mac', total: '$27.00', status: 'preparing', eta: '12m' },
    { id: '#A2916', cust: 'Sara L.',  items: 'Truffle flatbread · Caesar', total: '$38.00', status: 'preparing', eta: '4m' },
    { id: '#A2915', cust: 'Priya N.', items: '2× Pancakes · Benedict',     total: '$51.50', status: 'ready',     eta: '—' },
    { id: '#A2914', cust: 'Tom O.',   items: '4× Cookie · Risotto',         total: '$37.00', status: 'delivery',  eta: '6m' },
  ];
  const newOrder = { id: '#A2918', cust: 'Maya R.', items: '2× Honey-butter chicken · Lemonade', total: '$47.50', status: 'new', eta: '35m' };

  const statusStyles = {
    new:       { bg: '#FFE4CC', fg: '#9A3412', dot: '#F97316', label: 'New' },
    preparing: { bg: '#FEF3C7', fg: '#92400E', dot: '#F59E0B', label: 'Preparing' },
    ready:     { bg: '#DCFCE7', fg: '#166534', dot: '#16A34A', label: 'Ready' },
    delivery:  { bg: '#EDE9FE', fg: '#5B21B6', dot: '#8B5CF6', label: 'Completed' },
  };

  return (
    <div style={{ padding: '24px 28px', height: '100%' }}>
      <SceneCaption
        eyebrow="Scene 01 · operations"
        title="A new order arrives. Your team already knows."
        sub="Live queue, instant notifications, no tablet juggling."
        active={active}
      />

      <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr 280px', gap: 16 }}>
        {/* Queue */}
        <div style={{
          background: DT_CREAM, border: `1px solid ${DT_BORDER}`, borderRadius: 14,
          overflow: 'hidden',
        }}>
          <div style={{
            padding: '12px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            borderBottom: `1px solid ${DT_BORDER}`, background: 'rgba(28,16,9,0.02)',
          }}>
            <span style={{ fontFamily: DT_FN, fontWeight: 800, fontSize: 13.5 }}>Order queue</span>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '3px 8px', borderRadius: 999,
              background: '#DCFCE7', color: '#166534',
              fontSize: 10.5, fontWeight: 700,
            }}>
              <span style={{ width: 5, height: 5, borderRadius: 99, background: '#22C55E',
                animation: 'dt-pulse 1.6s ease-in-out infinite' }}/>
              Live
            </span>
          </div>

          {/* New order row — slides in */}
          <div style={{
            display: 'grid', gridTemplateColumns: '78px 1fr 80px 90px 40px',
            padding: '14px 18px 14px 15px', alignItems: 'center',
            background: DT_AMBER_SOFT,
            borderLeft: `3px solid ${DT_AMBER}`,
            borderBottom: `1px solid ${DT_BORDER}`,
            opacity: newOrderVisible ? 1 : 0,
            transform: newOrderVisible ? 'translateY(0)' : 'translateY(-30px)',
            transition: 'all .5s cubic-bezier(.2,.7,.3,1)',
          }}>
            <div>
              <div style={{ fontFamily: DT_FM, fontSize: 11.5, fontWeight: 600 }}>{newOrder.id}</div>
              <div style={{ fontSize: 10, color: DT_AMBER_DEEP, marginTop: 1, fontWeight: 700, fontFamily: DT_FM, letterSpacing: '0.06em' }}>JUST IN</div>
            </div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 600 }}>{newOrder.cust}</div>
              <div style={{ fontSize: 11, color: DT_DIM, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{newOrder.items}</div>
            </div>
            <div style={{ fontWeight: 700, fontSize: 12.5, fontVariantNumeric: 'tabular-nums' }}>{newOrder.total}</div>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '3px 8px', borderRadius: 999,
              background: statusStyles.new.bg, color: statusStyles.new.fg,
              fontSize: 10.5, fontWeight: 700,
            }}>
              <span style={{ width: 5, height: 5, borderRadius: 99, background: statusStyles.new.dot }}/>
              New
            </span>
            <span style={{ fontSize: 11, color: DT_DIM, fontWeight: 600, textAlign: 'right' }}>{newOrder.eta}</span>
          </div>

          {/* Existing rows shift down */}
          {baseRows.map((r, i) => {
            const s = statusStyles[r.status];
            return (
              <div key={r.id} style={{
                display: 'grid', gridTemplateColumns: '78px 1fr 80px 90px 40px',
                padding: '12px 18px', alignItems: 'center',
                borderBottom: i < baseRows.length - 1 ? `1px solid ${DT_BORDER}` : 'none',
                transition: 'all .3s ease',
              }}>
                <div>
                  <div style={{ fontFamily: DT_FM, fontSize: 11.5, fontWeight: 600 }}>{r.id}</div>
                  <div style={{ fontSize: 10, color: DT_DIM, marginTop: 1 }}>{(i+2)*4}m ago</div>
                </div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>{r.cust}</div>
                  <div style={{ fontSize: 11, color: DT_DIM, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.items}</div>
                </div>
                <div style={{ fontWeight: 700, fontSize: 12.5, fontVariantNumeric: 'tabular-nums' }}>{r.total}</div>
                <span style={{
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                  padding: '3px 8px', borderRadius: 999,
                  background: s.bg, color: s.fg,
                  fontSize: 10.5, fontWeight: 700,
                }}>
                  <span style={{ width: 5, height: 5, borderRadius: 99, background: s.dot }}/>
                  {s.label}
                </span>
                <span style={{ fontSize: 11, color: DT_DIM, fontWeight: 600, textAlign: 'right' }}>{r.eta}</span>
              </div>
            );
          })}
        </div>

        {/* Side panel: notification + stats */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* Notification card — slides in */}
          <div style={{
            background: DT_INK, color: DT_CREAM, borderRadius: 12,
            padding: '14px 16px',
            boxShadow: '0 16px 36px rgba(28,16,9,0.25)',
            opacity: newOrderVisible ? 1 : 0,
            transform: newOrderVisible ? 'translateX(0)' : 'translateX(40px)',
            transition: 'all .5s cubic-bezier(.2,.7,.3,1) .15s',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <span style={{
                width: 28, height: 28, borderRadius: 8,
                background: DT_AMBER, color: DT_INK,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 14,
              }}>🔔</span>
              <span style={{ fontFamily: DT_FN, fontWeight: 800, fontSize: 12 }}>Order incoming</span>
            </div>
            <div style={{ fontSize: 11.5, color: 'rgba(255,251,245,0.7)', lineHeight: 1.4 }}>
              Maya R. · $47.50 · delivery · ETA 35 min
            </div>
            <button style={{
              marginTop: 10, padding: '6px 12px', border: 0, borderRadius: 7,
              background: DT_AMBER, color: DT_INK, fontFamily: DT_FN, fontWeight: 800, fontSize: 11.5,
              cursor: 'pointer', width: '100%',
            }}>Accept</button>
          </div>

          {/* Today summary */}
          <div style={{
            background: DT_CREAM, border: `1px solid ${DT_BORDER}`, borderRadius: 12,
            padding: '14px 16px',
          }}>
            <div style={{ fontFamily: DT_FM, fontSize: 10, color: DT_DIM, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 8 }}>
              Today · so far
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <Row k="Orders"   v={newOrderVisible ? '47' : '46'} pop={newOrderVisible}/>
              <Row k="Revenue"  v={newOrderVisible ? '$2,184' : '$2,136'} pop={newOrderVisible}/>
              <Row k="Avg prep" v="14m"/>
              <Row k="Active"   v={newOrderVisible ? '6' : '5'} pop={newOrderVisible}/>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Row({ k, v, pop }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
      <span style={{ color: DT_DIM }}>{k}</span>
      <span style={{
        fontWeight: 700, fontVariantNumeric: 'tabular-nums',
        color: pop ? DT_AMBER_DEEP : DT_INK,
        transition: 'color .4s ease',
      }}>{v}</span>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 2 — AI generating menu description
// ═══════════════════════════════════════════════════════════════════════════
function SceneAI({ active, progress }) {
  const startTyping = active && progress > 0.18;
  const text = "Buttermilk stack, fluffy in the middle, lacy on the edges, layered with caramelised banana and Vermont maple. Comes with soft butter on the side — the way it should.";
  const typed = useTypewriter(text, startTyping, 18);
  const done = typed.length >= text.length;

  return (
    <div style={{ padding: '24px 28px', height: '100%' }}>
      <SceneCaption
        eyebrow="Scene 02 · AI menu studio"
        soon
        title="Menus that sell themselves — in your voice."
        sub="Pick a tone. The AI writes, translates, and enhances photos."
        active={active}
      />

      <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Left: source item */}
        <div style={{
          background: DT_CREAM, border: `1px solid ${DT_BORDER}`, borderRadius: 14,
          padding: 18,
        }}>
          <div style={{ fontFamily: DT_FM, fontSize: 10, color: DT_DIM, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 10 }}>Source item</div>
          <div style={{ display: 'flex', gap: 12 }}>
            <div style={{
              width: 60, height: 60, borderRadius: 10, flexShrink: 0,
              background: `linear-gradient(135deg, ${DT_AMBER_TINT}, ${DT_AMBER_SOFT})`,
              position: 'relative', overflow: 'hidden',
            }}>
              <div style={{
                position: 'absolute', inset: 0,
                background: 'repeating-linear-gradient(45deg, transparent 0 4px, rgba(249,115,22,0.18) 4px 8px)',
              }}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: DT_FN, fontWeight: 800, fontSize: 14, letterSpacing: '-0.01em' }}>
                Maple-banana pancakes
              </div>
              <div style={{ fontSize: 11.5, color: DT_DIM, marginTop: 2 }}>
                Brunch · $13.50
              </div>
              <div style={{ display: 'flex', gap: 4, marginTop: 6 }}>
                {['Sweet', 'Comfort', 'Local syrup'].map(t => (
                  <span key={t} style={{
                    padding: '2px 7px', borderRadius: 999,
                    background: DT_AMBER_SOFT, color: DT_AMBER_DEEP,
                    fontSize: 10, fontWeight: 600,
                  }}>{t}</span>
                ))}
              </div>
            </div>
          </div>

          <div style={{
            marginTop: 16, padding: '10px 12px', borderRadius: 8,
            background: 'rgba(28,16,9,0.03)',
            fontSize: 12, color: DT_DIM, lineHeight: 1.5, fontStyle: 'italic',
          }}>
            "fluffy pancakes with banana and maple syrup, butter on side"
            <div style={{ fontSize: 10, color: DT_DIM, marginTop: 4, fontStyle: 'normal', fontFamily: DT_FM, letterSpacing: '0.06em' }}>
              CURRENT DESCRIPTION · 1 LINE
            </div>
          </div>

          <div style={{ marginTop: 14 }}>
            <div style={{ fontFamily: DT_FM, fontSize: 10, color: DT_DIM, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 6 }}>Voice</div>
            <div style={{ display: 'flex', gap: 4, padding: 3, borderRadius: 8, background: 'rgba(28,16,9,0.05)' }}>
              {['Warm', 'Plain', 'Bold'].map((v, i) => (
                <button key={v} style={{
                  flex: 1, padding: '6px 8px', border: 0, borderRadius: 6,
                  background: i === 0 ? DT_CREAM : 'transparent',
                  color: i === 0 ? DT_INK : DT_DIM,
                  fontFamily: DT_FB, fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
                  boxShadow: i === 0 ? '0 1px 2px rgba(28,16,9,0.1)' : 'none',
                }}>{v}</button>
              ))}
            </div>
          </div>
        </div>

        {/* Right: AI generation */}
        <div style={{
          background: 'linear-gradient(135deg, rgba(249,115,22,0.06), rgba(219,39,119,0.04))',
          border: `1px solid rgba(249,115,22,0.2)`,
          borderRadius: 14, padding: 18, position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6, marginBottom: 12,
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: 6,
              background: `linear-gradient(135deg, ${DT_AMBER}, ${DT_BERRY})`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <span style={{ color: DT_CREAM, fontSize: 11 }}>✦</span>
            </div>
            <span style={{
              fontFamily: DT_FM, fontSize: 10, color: DT_AMBER_DEEP,
              letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 700,
            }}>AI · drafting (warm)</span>
            {startTyping && !done && (
              <span style={{
                marginLeft: 'auto', fontSize: 10, color: DT_AMBER_DEEP,
                display: 'inline-flex', gap: 2, alignItems: 'center',
              }}>
                <span style={{ width: 4, height: 4, borderRadius: 99, background: DT_AMBER_DEEP, animation: 'dt-dot 1.2s ease-in-out infinite' }}/>
                <span style={{ width: 4, height: 4, borderRadius: 99, background: DT_AMBER_DEEP, animation: 'dt-dot 1.2s ease-in-out .2s infinite' }}/>
                <span style={{ width: 4, height: 4, borderRadius: 99, background: DT_AMBER_DEEP, animation: 'dt-dot 1.2s ease-in-out .4s infinite' }}/>
              </span>
            )}
          </div>

          <p style={{
            margin: 0, fontFamily: DT_FN, fontWeight: 600, fontSize: 14.5,
            lineHeight: 1.55, color: DT_INK, minHeight: 130, textWrap: 'pretty',
          }}>
            {typed}
            {startTyping && !done && (
              <span style={{ display: 'inline-block', width: 2, height: 16, background: DT_AMBER_DEEP, marginLeft: 2, verticalAlign: 'middle', animation: 'dt-caret 1s steps(1) infinite' }}/>
            )}
          </p>

          {done && (
            <div style={{
              marginTop: 16, paddingTop: 14,
              borderTop: '1px dashed rgba(249,115,22,0.3)',
              display: 'flex', gap: 8, alignItems: 'center',
              animation: 'dt-fadein .4s ease',
            }}>
              <button style={{
                padding: '7px 14px', border: 0, borderRadius: 7,
                background: DT_INK, color: DT_CREAM,
                fontFamily: DT_FB, fontSize: 12, fontWeight: 600, cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                ✓ Use this
              </button>
              <button style={{
                padding: '7px 12px', border: `1px solid rgba(28,16,9,0.12)`,
                borderRadius: 7, background: DT_CREAM, color: DT_INK,
                fontFamily: DT_FB, fontSize: 12, fontWeight: 600, cursor: 'pointer',
              }}>Try another</button>
              <span style={{ marginLeft: 'auto', fontFamily: DT_FM, fontSize: 10, color: DT_DIM }}>
                Generated in 1.4s
              </span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 3 — Loyalty member growth
// ═══════════════════════════════════════════════════════════════════════════
function SceneLoyalty({ active, progress }) {
  const members = useAnimatedNumber(1247, active && progress > 0.1, 2200);
  const newJoinVisible = active && progress > 0.55;

  return (
    <div style={{ padding: '24px 28px', height: '100%' }}>
      <SceneCaption
        eyebrow="Scene 03 · loyalty"
        soon
        title="Regulars who actually come back."
        sub="Built-in loyalty program. No third-party app, no QR card to lose."
        active={active}
      />

      <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 16 }}>
        {/* Member chart */}
        <div style={{
          background: DT_CREAM, border: `1px solid ${DT_BORDER}`, borderRadius: 14,
          padding: 20,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
            <div>
              <div style={{ fontFamily: DT_FM, fontSize: 10, color: DT_DIM, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600 }}>
                Loyalty members
              </div>
              <div style={{
                fontFamily: DT_FN, fontWeight: 900, fontSize: 38,
                letterSpacing: '-0.03em', color: DT_INK, marginTop: 4,
              }}>
                {Math.round(members).toLocaleString()}
              </div>
              <div style={{ fontSize: 11.5, color: DT_FOREST, marginTop: 2, fontWeight: 600 }}>
                ↑ +47 this week
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {['7d', '30d', '90d'].map((v, i) => (
                <span key={v} style={{
                  padding: '4px 10px', borderRadius: 6,
                  background: i === 1 ? DT_INK : 'transparent',
                  color: i === 1 ? DT_CREAM : DT_DIM,
                  fontFamily: DT_FB, fontSize: 11, fontWeight: 600,
                  cursor: 'pointer',
                }}>{v}</span>
              ))}
            </div>
          </div>

          {/* Bar chart */}
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 140, paddingTop: 8 }}>
            {[18, 22, 19, 28, 32, 26, 38, 42, 36, 48, 52, 47, 58, 64].map((h, i) => (
              <div key={i} style={{
                flex: 1, borderRadius: '4px 4px 0 0',
                background: i === 13 ? DT_AMBER : DT_AMBER_TINT,
                height: active ? `${h * 2}px` : '0px',
                transition: `height .8s cubic-bezier(.2,.7,.3,1) ${i * 60}ms`,
                position: 'relative',
              }}>
                {i === 13 && (
                  <span style={{
                    position: 'absolute', top: -22, left: '50%', transform: 'translateX(-50%)',
                    fontFamily: DT_FN, fontWeight: 800, fontSize: 10, color: DT_AMBER_DEEP,
                    whiteSpace: 'nowrap',
                  }}>+47</span>
                )}
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontFamily: DT_FM, fontSize: 10, color: DT_DIM }}>
            <span>Apr 14</span><span>Apr 21</span><span>Apr 28</span>
          </div>
        </div>

        {/* Right: member card + just-joined */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{
            background: DT_INK, color: DT_CREAM, borderRadius: 14,
            padding: 18, position: 'relative', overflow: 'hidden',
          }}>
            <div aria-hidden style={{
              position: 'absolute', right: -40, top: -40,
              width: 160, height: 160, borderRadius: '50%',
              background: `radial-gradient(circle, ${DT_AMBER} 0%, transparent 65%)`,
              opacity: 0.4,
            }}/>
            <div style={{ position: 'relative' }}>
              <div style={{ fontFamily: DT_FM, fontSize: 9.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(255,251,245,0.55)' }}>
                RobinRun loyalty · gold
              </div>
              <div style={{ fontFamily: DT_FN, fontWeight: 900, fontSize: 19, marginTop: 6, letterSpacing: '-0.01em' }}>
                Maya R.
              </div>
              <div style={{
                marginTop: 14, display: 'flex', alignItems: 'baseline', gap: 5,
                fontFamily: DT_FN, fontWeight: 900, color: DT_AMBER,
                letterSpacing: '-0.03em', lineHeight: 1,
              }}>
                <span style={{ fontSize: 32 }}>1,240</span>
                <span style={{ fontSize: 12, color: 'rgba(255,251,245,0.6)', paddingBottom: 4 }}>pts</span>
              </div>
              <div style={{ marginTop: 12, height: 5, borderRadius: 99, background: 'rgba(255,251,245,0.1)' }}>
                <div style={{
                  width: active ? '62%' : '0%',
                  height: '100%', borderRadius: 99,
                  background: `linear-gradient(90deg, ${DT_AMBER}, ${DT_BERRY})`,
                  transition: 'width 1.6s cubic-bezier(.2,.7,.3,1)',
                }}/>
              </div>
              <div style={{ marginTop: 6, fontSize: 10.5, color: 'rgba(255,251,245,0.55)' }}>
                760 pts to <strong style={{ color: DT_CREAM }}>Platinum</strong>
              </div>
            </div>
          </div>

          {/* Just joined card */}
          <div style={{
            background: DT_CREAM, border: `1px solid ${DT_BORDER}`, borderRadius: 12,
            padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
            opacity: newJoinVisible ? 1 : 0,
            transform: newJoinVisible ? 'translateY(0)' : 'translateY(20px)',
            transition: 'all .5s cubic-bezier(.2,.7,.3,1)',
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: '50%',
              background: DT_FOREST, color: DT_CREAM,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: DT_FN, fontWeight: 800, fontSize: 13,
            }}>EM</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: DT_FN, fontWeight: 800, fontSize: 12.5 }}>Elena M. just joined</div>
              <div style={{ fontSize: 10.5, color: DT_DIM, marginTop: 1 }}>+50 welcome points · QR scan</div>
            </div>
            <span style={{ fontSize: 14 }}>🎉</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 4 — Revenue chart growing
// ═══════════════════════════════════════════════════════════════════════════
function SceneRevenue({ active, progress }) {
  const revenue = useAnimatedNumber(4847, active && progress > 0.1, 2000);
  const chartProgress = active ? Math.min(1, progress * 2.5) : 0;

  // Build path
  const points = [
    [0, 78], [60, 72], [120, 70], [180, 60], [240, 58],
    [300, 50], [360, 42], [420, 38], [480, 32], [540, 24],
    [600, 18], [660, 14], [720, 10], [780, 6],
  ];
  const fullPath = `M ${points.map(p => p.join(' ')).join(' L ')}`;
  const fillPath = `M 0 90 L ${points.map(p => p.join(' ')).join(' L ')} L 780 90 Z`;

  return (
    <div style={{ padding: '24px 28px', height: '100%' }}>
      <SceneCaption
        eyebrow="Scene 04 · sales analytics"
        title="Watch the line go up. Actually."
        sub="Sample data — revenue by channel, updated as orders come in."
        active={active}
      />

      <div style={{ marginTop: 24 }}>
        {/* Top stat row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
          {[
            { k: 'Today', v: `$${Math.round(revenue).toLocaleString()}`, delta: '+18%', emph: true },
            { k: 'Online', v: '$2,184', delta: '+24%' },
            { k: 'Dine-in', v: '$1,847', delta: '+8%' },
            { k: 'Pickup',  v: '$816',  delta: '+12%' },
          ].map((s, i) => (
            <div key={s.k} style={{
              background: s.emph ? DT_INK : DT_CREAM,
              color: s.emph ? DT_CREAM : DT_INK,
              border: s.emph ? 'none' : `1px solid ${DT_BORDER}`,
              borderRadius: 12, padding: '14px 16px',
            }}>
              <div style={{
                fontFamily: DT_FM, fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase',
                color: s.emph ? 'rgba(255,251,245,0.55)' : DT_DIM, fontWeight: 600,
              }}>{s.k}</div>
              <div style={{
                fontFamily: DT_FN, fontWeight: 900, fontSize: s.emph ? 24 : 20,
                letterSpacing: '-0.025em', marginTop: 4,
                color: s.emph ? DT_AMBER : DT_INK,
                fontVariantNumeric: 'tabular-nums',
              }}>{s.v}</div>
              <div style={{
                fontSize: 10.5, marginTop: 2,
                color: s.emph ? '#86EFAC' : DT_FOREST, fontWeight: 600,
              }}>{s.delta} vs yesterday</div>
            </div>
          ))}
        </div>

        {/* Chart */}
        <div style={{
          background: DT_CREAM, border: `1px solid ${DT_BORDER}`, borderRadius: 14,
          padding: 18,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <span style={{ fontFamily: DT_FN, fontWeight: 800, fontSize: 13.5 }}>30-day revenue</span>
            <span style={{ fontFamily: DT_FM, fontSize: 10.5, color: DT_DIM, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              ↑ 32% vs last month
            </span>
          </div>
          <svg viewBox="0 0 780 100" preserveAspectRatio="none" style={{ width: '100%', height: 200 }}>
            <defs>
              <linearGradient id="dt-rev-fill" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0" stopColor={DT_AMBER} stopOpacity="0.3"/>
                <stop offset="1" stopColor={DT_AMBER} stopOpacity="0"/>
              </linearGradient>
              <clipPath id="dt-rev-clip">
                <rect x="0" y="0" width={780 * chartProgress} height="100"/>
              </clipPath>
            </defs>
            <g clipPath="url(#dt-rev-clip)">
              <path d={fillPath} fill="url(#dt-rev-fill)"/>
              <path d={fullPath} fill="none" stroke={DT_AMBER} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
            </g>
            {/* End dot */}
            {chartProgress > 0.95 && (
              <g>
                <circle cx="780" cy="6" r="6" fill={DT_AMBER} opacity="0.3"/>
                <circle cx="780" cy="6" r="3" fill={DT_AMBER}/>
              </g>
            )}
          </svg>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 5 — Sending a campaign
// ═══════════════════════════════════════════════════════════════════════════
function SceneCampaign({ active, progress }) {
  const sentVisible = active && progress > 0.65;
  const recipients = useAnimatedNumber(284, sentVisible, 1200);
  const revenueEst = useAnimatedNumber(942, sentVisible, 1400);

  return (
    <div style={{ padding: '24px 28px', height: '100%' }}>
      <SceneCaption
        eyebrow="Scene 05 · promotions"
        soon
        title="Send a promotion in three taps."
        sub="Segment by behaviour. SMS or email. Sample data shown."
        active={active}
      />

      <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Left: builder */}
        <div style={{
          background: DT_CREAM, border: `1px solid ${DT_BORDER}`, borderRadius: 14,
          padding: 18,
          opacity: sentVisible ? 0.6 : 1,
          transition: 'opacity .4s ease',
        }}>
          <div style={{ fontFamily: DT_FM, fontSize: 10, color: DT_DIM, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 12 }}>
            Campaign · brunch regulars
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <Field label="Segment">
              <span style={{ fontWeight: 600 }}>Brunch regulars</span>
              <span style={{ color: DT_DIM, marginLeft: 6 }}>· ordered ≥3× in 30d</span>
              <span style={{ marginLeft: 'auto', fontFamily: DT_FM, fontSize: 11, color: DT_AMBER_DEEP, fontWeight: 700 }}>284</span>
            </Field>
            <Field label="Channel">
              <span style={{
                padding: '4px 9px', borderRadius: 6, fontSize: 11.5, fontWeight: 600,
                background: DT_AMBER_SOFT, color: DT_AMBER_DEEP,
              }}>Push</span>
            </Field>
            <Field label="When">
              <span style={{ fontWeight: 600 }}>Right now</span>
            </Field>
            <div style={{
              marginTop: 4, padding: 12, borderRadius: 10,
              background: DT_INK, color: DT_CREAM,
              display: 'flex', gap: 10, alignItems: 'flex-start',
            }}>
              <div style={{
                width: 26, height: 26, borderRadius: 7,
                background: `linear-gradient(135deg, ${DT_AMBER}, ${DT_AMBER_DEEP})`,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <RobinRunMark size={18} birdColor={DT_CREAM} birdShade={DT_PAPER} inkColor={DT_INK}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ fontFamily: DT_FN, fontWeight: 800, fontSize: 11.5 }}>RobinRun</span>
                  <span style={{ fontSize: 10, color: 'rgba(255,251,245,0.45)' }}>now</span>
                </div>
                <div style={{ fontSize: 11.5, marginTop: 2, lineHeight: 1.4 }}>
                  Saturday brunch is back at Golden Karahi 🥞 Free naan with your usual — today only.
                </div>
              </div>
            </div>
            <button style={{
              padding: '11px', border: 0, borderRadius: 10,
              background: sentVisible ? DT_FOREST : DT_AMBER,
              color: DT_CREAM, fontFamily: DT_FN, fontWeight: 800, fontSize: 13,
              cursor: 'pointer',
              transition: 'background .3s ease',
              boxShadow: sentVisible ? 'none' : `0 6px 16px ${DT_AMBER}55`,
            }}>
              {sentVisible ? '✓ Sent to 284 customers' : 'Send now'}
            </button>
          </div>
        </div>

        {/* Right: results */}
        <div style={{
          background: sentVisible
            ? `linear-gradient(135deg, ${DT_AMBER_SOFT}, ${DT_AMBER_TINT})`
            : DT_CREAM,
          border: `1px solid ${sentVisible ? DT_AMBER : DT_BORDER}`,
          borderRadius: 14, padding: 18,
          transition: 'all .4s ease',
          display: 'flex', flexDirection: 'column',
        }}>
          <div style={{ fontFamily: DT_FM, fontSize: 10, color: DT_DIM, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 14 }}>
            Live results
          </div>
          <div style={{
            opacity: sentVisible ? 1 : 0.3,
            transition: 'opacity .4s ease',
            display: 'flex', flexDirection: 'column', gap: 18, flex: 1,
          }}>
            <div>
              <div style={{ fontSize: 11, color: DT_DIM }}>Delivered</div>
              <div style={{ fontFamily: DT_FN, fontWeight: 900, fontSize: 36, letterSpacing: '-0.025em' }}>
                {Math.round(recipients)}
              </div>
              <div style={{ height: 4, borderRadius: 99, background: 'rgba(28,16,9,0.08)', marginTop: 4 }}>
                <div style={{
                  width: sentVisible ? '100%' : '0%',
                  height: '100%', borderRadius: 99, background: DT_AMBER,
                  transition: 'width 1s ease',
                }}/>
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: DT_DIM }}>Opened</div>
              <div style={{ fontFamily: DT_FN, fontWeight: 900, fontSize: 28, letterSpacing: '-0.025em' }}>
                {Math.round(recipients * 0.48)}
                <span style={{ fontSize: 13, color: DT_FOREST, fontWeight: 700, marginLeft: 8 }}>48%</span>
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: DT_DIM }}>Est. revenue impact</div>
              <div style={{
                fontFamily: DT_FN, fontWeight: 900, fontSize: 36, letterSpacing: '-0.025em',
                color: DT_AMBER_DEEP,
              }}>
                ${Math.round(revenueEst).toLocaleString()}
              </div>
              <div style={{ fontSize: 11, color: DT_DIM, marginTop: 2 }}>
                tracked to this campaign in 24h
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, color: DT_DIM, marginBottom: 4, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
        {label}
      </div>
      <div style={{
        padding: '8px 12px', borderRadius: 8,
        border: `1px solid ${DT_BORDER}`, background: 'rgba(28,16,9,0.02)',
        fontSize: 12.5, color: DT_INK,
        display: 'flex', alignItems: 'center', gap: 4,
      }}>{children}</div>
    </div>
  );
}

// ── Scene caption (consistent across all 5) ────────────────────────────────
function SceneCaption({ eyebrow, title, sub, active, soon }) {
  return (
    <div style={{
      opacity: active ? 1 : 0,
      transform: active ? 'translateY(0)' : 'translateY(10px)',
      transition: 'all .5s cubic-bezier(.2,.7,.3,1)',
    }}>
      <div style={{
        fontFamily: DT_FM, fontSize: 10.5, color: DT_AMBER_DEEP,
        letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700,
      }}>{eyebrow}</div>
      {soon && (
        <span style={{
          display: 'inline-block', marginTop: 8,
          fontFamily: DT_FM, fontSize: 9.5, fontWeight: 700,
          letterSpacing: '0.1em', textTransform: 'uppercase',
          padding: '4px 8px', borderRadius: 6,
          background: 'rgba(28,16,9,0.06)', color: DT_MUTED,
        }}>Coming soon</span>
      )}
      <h3 style={{
        margin: '6px 0 4px', fontFamily: DT_FN, fontWeight: 900, fontSize: 22,
        letterSpacing: '-0.02em', color: DT_INK,
      }}>{title}</h3>
      <p style={{
        margin: 0, fontSize: 13, color: DT_MUTED, lineHeight: 1.45,
      }}>{sub}</p>
    </div>
  );
}

// ── Inject scene animations ────────────────────────────────────────────────
if (typeof document !== 'undefined' && !document.getElementById('dt-anims')) {
  const s = document.createElement('style');
  s.id = 'dt-anims';
  s.textContent = `
    @keyframes dt-pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.4; transform: scale(0.6); } }
    @keyframes dt-dot   { 0%, 80%, 100% { opacity: 0.3; } 40% { opacity: 1; } }
    @keyframes dt-caret { 50% { opacity: 0; } }
    @keyframes dt-fadein{ from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { DashboardTour });
