/* App shell: phone frame, status bar, header, bottom nav, Sarthi FAB, demo navigator, toast. */
const { useEffect: _ue, useState: _us } = React;

function StatusBar({ dark = false }) {
  const color = dark ? '#fff' : '#0F172A';
  return (
    <div className="h-11 px-6 flex items-center justify-between shrink-0 relative z-10"
         style={{ color }}>
      <div className="text-[15px] font-semibold tracking-tight tabular-nums">9:47</div>
      <div className="flex items-center gap-1.5">
        <Signal size={16} stroke={color}/>
        <Wifi size={16} stroke={color}/>
        <Battery size={22} stroke={color}/>
      </div>
    </div>
  );
}

function TopHeader({ name = 'Rajesh' }) {
  return (
    <div className="h-14 px-4 flex items-center justify-between border-b border-ink-200 bg-white shrink-0">
      <div className="flex items-center gap-3">
        <button type="button" aria-label="Menu"
                className="w-9 h-9 rounded-full bg-ink-100 grid place-items-center press"><Menu size={18}/></button>
        <div className="leading-tight">
          <div className="text-[11px] text-ink-500 font-medium">Namaste,</div>
          <div className="text-[15px] font-semibold text-ink-900">{name}</div>
        </div>
      </div>
      <div className="flex items-center gap-2">
        <div className="px-2.5 py-1 rounded-full bg-orange-50 border border-orange-100 flex items-center gap-1.5">
          <span className="w-1.5 h-1.5 rounded-full bg-sw-orange animate-pulse"></span>
          <span className="text-[11px] font-semibold text-sw-orange-dark">ONLINE</span>
        </div>
        <button type="button" aria-label="Notifications"
                className="w-9 h-9 rounded-full bg-ink-100 grid place-items-center relative press">
          <Bell size={18}/>
          <span className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-rose-500 ring-2 ring-white"></span>
        </button>
      </div>
    </div>
  );
}

function BottomNav({ active = 'home', onChange }) {
  const tabs = [
    { id: 'home',  label: 'Home',     I: Home,   sub: 'Active deliveries' },
    { id: 'ord',   label: 'Orders',   I: Pkg,    sub: 'Order history' },
    { id: 'earn',  label: 'Earnings', I: Wallet, sub: '₹487 today' },
    { id: 'perf',  label: 'Stats',    I: Chart,  sub: 'Performance' },
    { id: 'me',    label: 'Account',  I: User,   sub: 'Profile & settings' },
  ];
  return (
    <div className="h-16 bg-white border-t border-ink-200 grid grid-cols-5 shrink-0"
         style={{ paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}>
      {tabs.map(({ id, label, I, sub }) => {
        const on = id === active;
        return (
          <button key={id} type="button"
                  onClick={() => { if (id === 'home') onChange?.('home'); }}
                  className="flex flex-col items-center justify-center gap-0.5 press">
            <I size={20} stroke={on ? '#FC8019' : '#64748B'} sw={on ? 2.2 : 1.8}/>
            <span className={`text-[10px] font-semibold ${on ? 'text-sw-orange-dark' : 'text-ink-500'}`}>{label}</span>
          </button>
        );
      })}
    </div>
  );
}

function SarthiFAB({ onHoldStart, onHoldEnd, showLabel, holding = false }) {
  const handleDown = (e) => {
    e.preventDefault();
    onHoldStart?.();
  };

  return (
    <div className="absolute right-4 bottom-20 z-30 flex items-center gap-2">
      {showLabel && !holding && (
        <div className="px-3 py-1.5 rounded-full bg-ink-900 text-white text-[11px] font-medium shadow-lift fade-in flex items-center gap-1.5">
          <Sparkles size={12} stroke="#FBBF24"/>
          <span>Hold &amp; speak to Sarthi</span>
          <div className="w-0 h-0 absolute -right-1 top-1/2 -translate-y-1/2"
               style={{ borderTop: '6px solid transparent', borderBottom: '6px solid transparent', borderLeft: '6px solid #0F172A' }}/>
        </div>
      )}
      {holding && (
        <div className="px-3 py-1.5 rounded-full bg-sarthi-from text-white text-[11px] font-semibold shadow-lift fade-in">
          Listening…
        </div>
      )}
      <button
        onPointerDown={handleDown}
        onContextMenu={(e) => e.preventDefault()}
        className={`sarthi-fab relative rounded-full grid place-items-center text-white select-none touch-none
          ${holding ? 'scale-110' : 'press'}`}
        style={{ transition: 'transform 120ms ease' }}
        aria-label="Hold to talk to Sarthi"
      >
        <div className={`absolute inset-0 rounded-full orb-grad shadow-orb ${holding ? 'orb-pulse-lg' : 'orb-pulse'}`}></div>
        <div className="absolute inset-0 rounded-full pointer-events-none"
             style={{ background: 'radial-gradient(ellipse at 30% 25%, rgba(255,255,255,0.55) 0%, rgba(255,255,255,0) 50%)' }}/>
        <div className="relative z-10 sarthi-fab-icon"><Mic size={26} stroke="#fff" sw={2.2}/></div>
      </button>
    </div>
  );
}

/* Phone frame wraps everything. At desktop: dark bezel + notch. At mobile: full bleed. */
function PhoneFrame({ children }) {
  return (
    <div className="phone-bezel relative shrink-0">
      <div className="phone-notch"></div>
      <div className="phone-screen relative overflow-hidden bg-surface">
        {children}
      </div>
    </div>
  );
}

/* Host wrapper: desktop storyboard + phone; mobile strip above phone */
function AppLayout({ children, side, mobileStory, screen }) {
  return (
    <div className="phone-host w-full min-h-screen flex items-center justify-center md:p-8 relative">
      <style>{`
        .phone-host {
          background:
            radial-gradient(1200px 600px at 15% 0%, rgba(252,128,25,0.08) 0%, rgba(252,128,25,0) 60%),
            radial-gradient(1000px 600px at 100% 100%, rgba(255,138,61,0.06) 0%, rgba(255,138,61,0) 60%),
            linear-gradient(180deg, #F8FAFC 0%, #EEF2F7 100%);
        }
        .phone-screen { width: 100vw; max-width: 100vw; height: 100vh; max-height: 100vh; }
        .phone-bezel { width: 100%; }
        .phone-notch { display: none; }
        @media (min-width: 768px) {
          .phone-bezel {
            width: 412px;
            background: #111418;
            border-radius: 48px;
            padding: 12px;
            box-shadow: 0 40px 80px -20px rgba(15,23,42,0.35), 0 20px 40px -20px rgba(15,23,42,0.25), inset 0 0 0 1.5px #2A2F36;
          }
          .phone-screen { width: 388px; height: 820px; max-height: 820px; border-radius: 36px; }
          .phone-notch  { display: block; position: absolute; left: 50%; top: 18px; transform: translateX(-50%); width: 116px; height: 30px; background: #000; border-radius: 18px; z-index: 50; }
        }
      `}</style>
      <div className="w-full flex flex-col items-center max-w-[1280px] mx-auto pt-12 md:pt-0">
        {mobileStory}
        <div className="w-full md:w-auto flex flex-col md:flex-row items-center justify-center gap-8 md:gap-14">
          <div className="hidden md:block w-[420px] shrink-0">{side}</div>
          {children}
        </div>
      </div>
    </div>
  );
}

/* ---------- Flow description (desktop side panel) ---------- */

const FLOW_INFO = {
  A: {
    badge: 'Flow A',
    title: 'Conversational onboarding',
    pitch: 'Replace skippable training videos with a 90-minute voice-led co-pilot that meets partners in their language.',
    accent: 'from-sarthi-from to-sarthi-to',
    persona: 'Rajesh Kamble · Day 0 · Pune',
    scenarios: [
      { t: '1', d: 'Picks Hindi from 8 Indian languages' },
      { t: '2', d: 'AI-vetted KYC: license + Aadhaar OCR' },
      { t: '3', d: 'Three voice scenarios — restaurant delay, customer abuse, wrong address' },
      { t: '4', d: 'Personalized first shift by zone & demand' },
    ],
    genai: [
      'Sarvam-1 (Hindi LLM) for in-language coaching',
      'Vision API for document OCR + liveness',
      'Bhashini STT for spoken scenario answers',
    ],
    metrics: [
      { v: '+18%', l: 'D1→D7 retention' },
      { v: '90 min', l: 'Time to first delivery' },
      { v: '−24%', l: 'Week-1 drop-off' },
    ],
  },
  B: {
    badge: 'Flow B',
    title: 'Voice-first crisis co-pilot',
    pitch: 'Long-press → speak naturally → Sarthi understands context, advises in Hindi, and takes agentic action on the partner\'s behalf.',
    accent: 'from-sarthi-from to-sarthi-to',
    persona: 'Rajesh Kamble · Mid-shift · Restaurant won\'t release order',
    scenarios: [
      { t: '①', d: 'Restaurant delay (this demo) — Sarthi notifies manager, SMSes customer, locks rating' },
      { t: '②', d: 'Customer abuse — Sarthi files incident, swaps to safe-mode language, escalates' },
      { t: '③', d: 'Wrong address — Sarthi calls customer, re-routes, recalculates payout' },
      { t: '④', d: 'App glitch — Sarthi captures session, files ticket, freezes payout clock' },
    ],
    genai: [
      'Real-time Hindi STT streamed to LLM',
      'Context-aware prompt: order state + partner history + restaurant SLA',
      'Agentic tool calls: notifyRestaurant, smsCustomer, freezeRating',
      'ElevenLabs "Anika" TTS for spoken reply',
    ],
    metrics: [
      { v: '< 8s', l: 'Time to resolution' },
      { v: '100%', l: 'Rating-safe outcomes' },
      { v: '+12 pts', l: 'Customer NPS' },
    ],
  },
  C: {
    badge: 'Flow C',
    title: 'Proactive coaching & growth',
    pitch: 'Sarthi reviews yesterday\'s shift and surfaces a 2-minute personalized audio with what top 5% partners do in similar situations.',
    accent: 'from-sarthi-from to-sarthi-to',
    persona: 'Rajesh Kamble · Day 7 · Morning brief',
    scenarios: [
      { t: '①', d: 'Daily AM brief generated from last shift events' },
      { t: '②', d: 'Tap-to-listen 2-min audio coaching' },
      { t: '③', d: 'Cross-sell to higher-paying categories (Instamart, parcels)' },
      { t: '④', d: 'Weekly skill milestones, unlocked progressively' },
    ],
    genai: [
      'Llama-3 fine-tuned on partner SOPs + transcript history',
      'Personalized audio scripts generated nightly per partner',
      'Earnings predictor compares category mix vs cohort',
    ],
    metrics: [
      { v: '64%', l: 'Coach completion' },
      { v: '+₹420', l: 'Week-1 earnings lift' },
      { v: '+8%', l: 'Category-mix shift' },
    ],
  },
};

function FlowDescription({ screen }) {
  const flow = screen[0];
  const info = FLOW_INFO[flow];
  if (!info) return null;

  return (
    <div className="screen-in side-text-base" key={flow}>
      {/* Wordmark */}
      <div className="flex items-center gap-2.5 mb-7">
        <SarthiOrb size={36}/>
        <div className="leading-tight">
          <div className="text-[20px] font-extrabold side-text-base text-ink-900 tracking-tight">Sarthi</div>
          <div className="text-[11px] side-text-muted text-ink-500 font-medium">AI co-pilot · Pace delivery partners</div>
        </div>
        <div className="ai-badge ml-auto px-2 py-1 rounded-full bg-sarthi-100 text-sarthi-deep text-[10px] font-bold uppercase tracking-wider">
          GenAI demo
        </div>
      </div>

      {/* Flow header */}
      <div className="flex items-center gap-2 mb-2">
        <span className={`text-[10px] font-bold uppercase tracking-[0.18em] bg-gradient-to-r ${info.accent} bg-clip-text text-transparent`}>
          {info.badge}
        </span>
        <span className="w-1 h-1 rounded-full bg-ink-300"></span>
        <span className="text-[10px] font-semibold uppercase tracking-wider side-text-muted text-ink-500">Screen {screen}</span>
      </div>
      <h1 className="text-[28px] font-extrabold side-text-base text-ink-900 tracking-tight leading-tight">{info.title}</h1>
      <p className="text-[14px] side-text-muted text-ink-700 leading-relaxed mt-2">{info.pitch}</p>

      {/* Persona */}
      <div className="side-card mt-5 rounded-xl bg-white border border-ink-200 px-3.5 py-2.5 flex items-center gap-3 shadow-card">
        <div className="w-9 h-9 rounded-full bg-amber-100 grid place-items-center font-bold text-amber-700 text-[13px] shrink-0">RK</div>
        <div className="leading-tight">
          <div className="text-[11px] side-text-muted text-ink-500 font-medium uppercase tracking-wider">Persona</div>
          <div className="text-[12px] font-semibold side-text-base text-ink-900">{info.persona}</div>
        </div>
      </div>

      {/* Scenarios */}
      <div className="mt-5">
        <div className="text-[11px] font-bold side-text-muted text-ink-500 uppercase tracking-wider mb-2">User scenarios</div>
        <div className="space-y-1.5">
          {info.scenarios.map((s, i) => (
            <div key={i} className="flex gap-2.5 items-start">
              <div className="side-surface w-5 h-5 rounded-md bg-ink-100 text-ink-700 grid place-items-center text-[10px] font-bold shrink-0">{s.t}</div>
              <div className="text-[12.5px] side-text-muted text-ink-700 leading-snug">{s.d}</div>
            </div>
          ))}
        </div>
      </div>

      {/* GenAI under the hood */}
      <div className="side-gen ai-extra mt-5 rounded-2xl border border-sarthi-100 bg-gradient-to-br from-sarthi-50 to-white p-3.5">
        <div className="flex items-center gap-1.5 mb-2">
          <Sparkles size={12} stroke="#6D28D9"/>
          <span className="text-[11px] font-bold uppercase tracking-wider text-sarthi-deep whitespace-nowrap">GenAI under the hood</span>
        </div>
        <div className="space-y-1.5">
          {info.genai.map((g, i) => (
            <div key={i} className="flex gap-2 items-start text-[12px] side-text-base text-ink-700 leading-snug">
              <div className="w-1 h-1 rounded-full mt-2 shrink-0" style={{ background: 'linear-gradient(135deg,var(--s-from),var(--s-to))' }}/>
              <div>{g}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Metrics */}
      <div className="mt-5 grid grid-cols-3 gap-2">
        {info.metrics.map((m, i) => (
          <div key={i} className="side-card rounded-xl bg-white border border-ink-200 p-2.5 text-center shadow-card">
            <div className="text-[16px] font-extrabold side-text-base text-ink-900 tracking-tight">{m.v}</div>
            <div className="text-[10px] side-text-muted text-ink-500 mt-0.5 leading-tight">{m.l}</div>
          </div>
        ))}
      </div>

      {/* Try-it hint */}
      <div className="side-cta mt-5 rounded-xl bg-ink-900 text-white p-3 flex items-center gap-2.5">
        <div className="w-7 h-7 rounded-full orb-grad grid place-items-center shrink-0"><Mic size={14} stroke="#fff"/></div>
        <div className="leading-tight">
          <div className="text-[12px] font-semibold">Try it →</div>
          <div className="text-[10px] text-white/60">Tap the Sarthi button on the phone to start a voice interaction.</div>
        </div>
      </div>
    </div>
  );
}

/* Demo Navigator — small floating pill, top-right of viewport. */
function DemoNavigator({ screen, goto }) {
  const flows = [
    { id: 'A', start: 'A1', label: 'Onboarding' },
    { id: 'B', start: 'B1', label: 'Crisis'     },
    { id: 'C', start: 'C1', label: 'Coaching'   },
  ];
  const current = screen[0];
  return (
    <div className="fixed top-3 right-3 z-50 flex items-center gap-1.5 bg-white/90 backdrop-blur-md border border-ink-200 rounded-full pl-2 pr-1 py-1 shadow-card">
      <span className="text-[10px] font-semibold text-ink-500 px-1 uppercase tracking-wider">Demo</span>
      {flows.map(f => {
        const on = current === f.id;
        return (
          <button key={f.id} onClick={() => goto(f.start)}
                  className={`px-2.5 py-1 rounded-full text-[11px] font-semibold press transition ${on ? 'bg-ink-900 text-white' : 'text-ink-700 hover:bg-ink-100'}`}>
            {f.label}
          </button>
        );
      })}
    </div>
  );
}

/* Toast (top, in-screen) */
function Toast({ text, sub, tone = 'sarthi' }) {
  const ring = tone === 'sarthi' ? 'from-sarthi-from to-sarthi-to' : 'from-pace-500 to-pace-600';
  return (
    <div className="absolute top-14 left-1/2 -translate-x-1/2 z-40 toast-in">
      <div className="bg-ink-900 text-white px-3 py-2 rounded-full flex items-center gap-2 shadow-lift">
        <div className={`w-5 h-5 rounded-full bg-gradient-to-br ${ring} grid place-items-center`}>
          <SpeakingDots size={10}/>
        </div>
        <div className="leading-tight">
          <div className="text-[12px] font-semibold">{text}</div>
          {sub && <div className="text-[10px] text-white/60">{sub}</div>}
        </div>
      </div>
    </div>
  );
}

/* Tiny in-screen confetti */
function Confetti() {
  const pieces = React.useMemo(() => Array.from({ length: 26 }).map((_, i) => {
    const colors = ['#8B5CF6', '#EC4899', '#F59E0B', '#10B981', '#06B6D4', '#F43F5E'];
    return {
      left: Math.random() * 100,
      cx: (Math.random() - 0.5) * 80,
      delay: Math.random() * 350,
      color: colors[i % colors.length],
      w: 6 + Math.random() * 6,
      h: 8 + Math.random() * 10,
      rot: Math.random() * 360,
    };
  }), []);
  return (
    <div className="absolute inset-0 pointer-events-none overflow-hidden z-30">
      {pieces.map((p, i) => (
        <div key={i} className="confetti-piece absolute"
             style={{
               left: `${p.left}%`, top: 0,
               width: p.w, height: p.h, background: p.color, borderRadius: 2,
               transform: `rotate(${p.rot}deg)`, animationDelay: `${p.delay}ms`,
               '--cx': `${p.cx}px`,
             }}/>
      ))}
    </div>
  );
}

Object.assign(window, {
  StatusBar, TopHeader, BottomNav, SarthiFAB, PhoneFrame, AppLayout, FlowDescription, DemoNavigator, Toast, Confetti,
});
