// app-embed.jsx — embeds the REAL ReturnScribe iOS prototype into the website.
// RSAppEmbed = the full interactive app (tabs, push navigation, sheets, paywall,
// splash) exactly as built in the app project, scaled into a phone frame.
// RSScreenFrame = a single real app screen in a static (non-interactive) phone.
// Both render the genuine screens from /app — no re-drawn mockups.

const { useState, useEffect, useRef, useMemo } = React;

function rsHexA(hex, a) {
  const h = hex.replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map((c) => c + c).join('') : h, 16);
  return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${a})`;
}

// Apply the chosen ink accent to the shared app tokens (same logic as the app shell).
function rsApplyAccent(accent) {
  const darkAccent = {
    '#C2451E': '#F0653A', '#3D6B9E': '#6FA3DC',
    '#3E8F7C': '#5FC3A9', '#7A5CA8': '#A98BE0',
  }[accent] || accent;
  RSTokens.dark.accent = darkAccent; RSTokens.dark.accentDim = rsHexA(darkAccent, 0.14);
  RSTokens.light.accent = accent;    RSTokens.light.accentDim = rsHexA(accent, 0.11);
}

// ── Push host: slides a detail screen over the tab layer (from the app shell) ──
function RSPushHost({ t, top, render }) {
  const [cur, setCur] = useState(top);
  const [vis, setVis] = useState(!!top);
  useEffect(() => {
    if (top) {
      setCur(top);
      let r2;
      const r1 = requestAnimationFrame(() => { r2 = requestAnimationFrame(() => setVis(true)); });
      return () => { cancelAnimationFrame(r1); cancelAnimationFrame(r2); };
    }
    setVis(false);
    const id = setTimeout(() => setCur(null), 340);
    return () => clearTimeout(id);
  }, [top]);
  if (!cur) return null;
  return (
    <div style={{
      position: 'absolute', top: 47, left: 0, right: 0, bottom: 0, zIndex: 40,
      background: t.canvas, overflowY: 'auto',
      transform: vis ? 'translateX(0)' : 'translateX(100%)',
      transition: 'transform 320ms cubic-bezier(.22,.61,.36,1)',
      boxShadow: vis ? '-12px 0 40px rgba(0,0,0,0.18)' : 'none',
      pointerEvents: vis ? 'auto' : 'none',
    }}>{render(cur)}</div>
  );
}

// ── The real app, embedded ──────────────────────────────────────
// Mirrors the App() shell from the app project's ReturnScribe.html, minus the
// project chrome. `request` lets the page trigger flows (splash / paywall /
// onboarding) from outside.
function RSAppShell({ dark, accent = '#C2451E', request = null, tabRequest = null, playSplash = true }) {
  window.RS_GLASS = window.RS_GLASS || 1.4;
  rsApplyAccent(accent);
  const t = dark ? RSTokens.dark : RSTokens.light;

  const [tab, setTab] = useState('home');
  const [stack, setStack] = useState([]);
  const [sheet, setSheet] = useState(null);
  const [modal, setModal] = useState(null);
  const [splash, setSplash] = useState(playSplash);
  const scrollRef = useRef(null);

  // outside-world requests (from the page's "demo controls")
  useEffect(() => {
    if (!request) return;
    if (request.type === 'splash') setSplash(true);
    if (request.type === 'paywall') setModal({ type: 'paywall', props: {} });
    if (request.type === 'onboarding') setModal({ type: 'onboarding', props: {} });
  }, [request]);

  // outside-world tab switching (expandable tabs on the page)
  useEffect(() => {
    if (!tabRequest) return;
    setStack([]);
    setTab(tabRequest.id);
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [tabRequest]);

  const nav = useMemo(() => ({
    push: (type, props) => setStack((s) => [...s, { type, props: props || {} }]),
    pop: () => setStack((s) => s.slice(0, -1)),
    openSheet: (type, props) => setSheet({ type, props: props || {} }),
    closeSheet: () => setSheet(null),
    openModal: (type, props) => setModal({ type, props: props || {} }),
    closeModal: () => setModal(null),
  }), []);

  const onTab = (id) => { setStack([]); setTab(id); if (scrollRef.current) scrollRef.current.scrollTop = 0; };

  function renderTab(id) {
    switch (id) {
      case 'home':     return <HomeScreen t={t} dark={dark} themeMode={dark ? 'dark' : 'light'} onThemeChange={() => {}} scrollRef={scrollRef} nav={nav}/>;
      case 'inbox':    return <InboxScreen t={t} nav={nav}/>;
      case 'subs':     return <SubsScreen t={t} nav={nav}/>;
      case 'refunds':  return <RefundsScreen t={t} nav={nav}/>;
      case 'settings': return <SettingsScreen t={t} dark={dark} themeMode={dark ? 'dark' : 'light'} onThemeChange={() => {}} nav={nav}/>;
      default: return null;
    }
  }
  function renderPushed(s) {
    if (s.type === 'purchase') return <PurchaseDetailScreen t={t} purchase={s.props.purchase} nav={nav}/>;
    if (s.type === 'sub')      return <SubscriptionDetailScreen t={t} sub={s.props.sub} nav={nav}/>;
    return null;
  }

  const top = stack[stack.length - 1] || null;

  return (
    <div className="rs-phone" style={{
      width: 393, height: 852, borderRadius: 50, overflow: 'hidden', position: 'relative',
      background: t.canvas, color: t.text1,
      boxShadow: dark
        ? '0 50px 100px rgba(0,0,0,0.6), 0 0 0 1px rgba(239,233,222,0.1)'
        : '0 40px 90px rgba(42,38,32,0.45), 0 0 0 1px rgba(33,29,23,0.18)',
      fontFamily: RSFont.sys, WebkitFontSmoothing: 'antialiased',
      transition: 'background 300ms ease',
    }}>
      {/* paper grain — faint ruled texture */}
      <div style={{
        position: 'absolute', inset: 0, zIndex: 0, pointerEvents: 'none', opacity: dark ? 0.05 : 0.5,
        background: `repeating-linear-gradient(0deg, transparent 0 31px, ${dark ? 'rgba(239,233,222,0.35)' : 'rgba(33,29,23,0.045)'} 31px 32px)`,
      }}></div>
      {/* dynamic island */}
      <div style={{ position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)', width: 120, height: 34, borderRadius: 22, background: '#000', zIndex: 51 }}/>
      <StatusBar dark={dark}/>

      <div ref={scrollRef} key={tab} style={{
        position: 'absolute', top: 47, left: 0, right: 0, bottom: 0,
        overflowY: 'auto', paddingBottom: 100,
      }}>{renderTab(tab)}</div>

      <RSPushHost t={t} top={top} render={renderPushed}/>

      {!top && <AnimatedTabBar t={t} active={tab} onChange={onTab}/>}

      {/* home indicator */}
      <div style={{ position: 'absolute', bottom: 8, left: 0, right: 0, zIndex: 70, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
        <div style={{ width: 134, height: 5, borderRadius: 100, background: dark ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.3)' }}/>
      </div>

      {/* sheets */}
      <SubEditSheet t={t} isNew open={sheet?.type === 'addSub'} onClose={() => setSheet(null)}
        sub={{ name: '', price: 0, cadence: 'monthly', next: '', trialDaysLeft: 0, cat: 'repeat.circle.fill', kind: 'active' }}
        onSave={() => {}}/>
      <DataExportSheet t={t} open={sheet?.type === 'export'} onClose={() => setSheet(null)}/>
      <DowngradeSheet t={t} open={sheet?.type === 'downgrade'} onClose={() => setSheet(null)}/>

      {/* modals */}
      <ModalCover t={t} open={modal?.type === 'paywall'}>
        <PaywallScreen t={t} onClose={() => setModal(null)}/>
      </ModalCover>
      <ModalCover t={t} open={modal?.type === 'onboarding'} z={95}>
        <OnboardingFlow t={t} onFinish={() => setModal(null)}/>
      </ModalCover>

      {/* opening splash — the app's real launch animation */}
      {splash && <SplashIntro t={t} onDone={() => setSplash(false)}/>}
    </div>
  );
}

// Scaled wrapper so the 393×852 prototype fits anywhere on the page.
function RSAppEmbed({ width = 320, dark = true, accent = '#C2451E', request = null, tabRequest = null, playSplash = true }) {
  const scale = width / 393;
  return (
    <div style={{ width: 393 * scale, height: 852 * scale, position: 'relative' }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: 'top left' }}>
        <RSAppShell dark={dark} accent={accent} request={request} tabRequest={tabRequest} playSplash={playSplash}/>
      </div>
    </div>
  );
}

// ── Static real-screen frame (for the scroll sequence) ──────────
const RS_NAV_NOOP = {
  push: () => {}, pop: () => {}, openSheet: () => {}, closeSheet: () => {},
  openModal: () => {}, closeModal: () => {},
};

const RS_STATIC_SCREENS = {
  home:    (t, dark) => <HomeScreen t={t} dark={dark} themeMode={dark ? 'dark' : 'light'} onThemeChange={() => {}} scrollRef={{ current: null }} nav={RS_NAV_NOOP}/>,
  settings:(t, dark) => <SettingsScreen t={t} dark={dark} themeMode={dark ? 'dark' : 'light'} onThemeChange={() => {}} nav={RS_NAV_NOOP}/>,
  connect: (t) => <MailboxConnectScreen t={t} onContinue={() => {}}/>,
  consent: (t) => <ConsentScreen t={t} onContinue={() => {}}/>,
  inbox:   (t) => <InboxScreen t={t} nav={RS_NAV_NOOP}/>,
  subs:    (t) => <SubsScreen t={t} nav={RS_NAV_NOOP}/>,
  refunds: (t) => <RefundsScreen t={t} nav={RS_NAV_NOOP}/>,
  detail:  (t) => <PurchaseDetailScreen t={t} purchase={RSData.inbox[1]} nav={RS_NAV_NOOP}/>,
};

// Onboarding screens were designed full-screen; nudge them below the island.
const RS_TOP_PAD = { connect: 30, consent: 30 };

function RSScreenFrame({ screen = 'inbox', width = 290, dark = true, accent = '#C2451E', active = true }) {
  rsApplyAccent(accent);
  const t = dark ? RSTokens.dark : RSTokens.light;
  const scale = width / 393;
  return (
    <div style={{ width: 393 * scale, height: 852 * scale, position: 'relative', pointerEvents: 'none' }} aria-hidden="true">
      <div style={{ transform: `scale(${scale})`, transformOrigin: 'top left' }}>
        <div className="rs-phone" style={{
          width: 393, height: 852, borderRadius: 50, overflow: 'hidden', position: 'relative',
          background: t.canvas, color: t.text1,
          boxShadow: dark
            ? '0 50px 100px rgba(0,0,0,0.6), 0 0 0 1px rgba(239,233,222,0.1)'
            : '0 40px 90px rgba(42,38,32,0.45), 0 0 0 1px rgba(33,29,23,0.18)',
          fontFamily: RSFont.sys, WebkitFontSmoothing: 'antialiased',
        }}>
          <div style={{
            position: 'absolute', inset: 0, zIndex: 0, pointerEvents: 'none', opacity: dark ? 0.05 : 0.5,
            background: `repeating-linear-gradient(0deg, transparent 0 31px, ${dark ? 'rgba(239,233,222,0.35)' : 'rgba(33,29,23,0.045)'} 31px 32px)`,
          }}></div>
          <div style={{ position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)', width: 120, height: 34, borderRadius: 22, background: '#000', zIndex: 51 }}/>
          <StatusBar dark={dark}/>
          <div style={{ position: 'absolute', top: 47, left: 0, right: 0, bottom: 0, overflow: 'hidden', paddingTop: RS_TOP_PAD[screen] || 0 }}>
            {(RS_STATIC_SCREENS[screen] || RS_STATIC_SCREENS.inbox)(t, dark)}
          </div>
          <div style={{ position: 'absolute', bottom: 8, left: 0, right: 0, zIndex: 70, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
            <div style={{ width: 134, height: 5, borderRadius: 100, background: dark ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.3)' }}/>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RSAppEmbed, RSScreenFrame, rsHexA, rsApplyAccent });
