// ─────────────────────────────────────────────────────────────
// Posy · Root: onboarding, router, scale-to-fit frame
// ─────────────────────────────────────────────────────────────

// ── Onboarding ──────────────────────────────────────────────
const AppOnboarding = ({ onComplete, hasGiftInUrl }) => {
  const [step, setStep] = React.useState(0);
  const [name, setName] = React.useState('');

  const proceed = () => {
    if (step === 0) { setStep(1); return; }
    if (step === 1) {
      if (!name.trim()) return;
      onComplete({ name: name.trim(), partner: '' });
    }
  };

  return (
    <Screen>
      <PhotoBackdrop />
      <div style={{ position: 'absolute', top: 200, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
        <svg width="240" height="340" viewBox="0 0 240 340" style={{ filter: 'saturate(1.15) contrast(1.05) drop-shadow(0 20px 40px rgba(0,0,0,0.6))' }}>
          <defs>
            <radialGradient id="onb-light-app" cx="50%" cy="20%" r="55%">
              <stop offset="0%" stopColor="rgba(255,200,140,0.32)" />
              <stop offset="100%" stopColor="rgba(255,200,140,0)" />
            </radialGradient>
          </defs>
          <rect width="240" height="340" fill="url(#onb-light-app)" />
          <g transform="translate(80 -10)"><Stem1 kind="peony" health={1} w={80} h={340} /></g>
        </svg>
      </div>
      <StatusBar />

      {step === 0 && (
        <>
          <div style={{ position: 'absolute', top: 100, left: 28, right: 28, textAlign: 'center' }}>
            <Caps>A small garden, between us</Caps>
          </div>
          <div style={{ position: 'absolute', top: 460, left: 28, right: 28, textAlign: 'center' }}>
            <div style={{ fontFamily: serif, fontStyle: 'italic', fontSize: 72, lineHeight: 0.95, color: PHOTO.bone, letterSpacing: '-0.02em' }}>
              Fleuraine
            </div>
            <div style={{ fontFamily: serif, fontStyle: 'italic', fontSize: 18, lineHeight: 1.35, color: PHOTO.boneDim, marginTop: 14, padding: '0 20px' }}>
              Flowers, sent slowly.<br />
              Cared for daily.<br />
              Kept forever.
            </div>
          </div>
          <div style={{ position: 'absolute', bottom: 80, left: 28, right: 28 }}>
            <button onClick={proceed} style={{
              width: '100%', background: PHOTO.bone, color: PHOTO.night, borderRadius: 999,
              border: 'none', padding: '18px 0', fontSize: 15, fontWeight: 600,
              cursor: 'pointer', fontFamily: sans, letterSpacing: '0.04em',
              boxShadow: `0 8px 28px rgba(0,0,0,0.5), 0 0 60px ${PHOTO.amberGlow}`,
            }}>
              {hasGiftInUrl ? 'Open your bouquet' : 'Begin'}
            </button>
            {hasGiftInUrl && (
              <div style={{ marginTop: 14, textAlign: 'center', fontFamily: serif, fontStyle: 'italic', fontSize: 14, color: PHOTO.boneDim }}>
                one is waiting for you
              </div>
            )}
          </div>
        </>
      )}

      {step === 1 && (
        <>
          <div style={{ position: 'absolute', top: 110, left: 28, right: 28 }}>
            <Caps>First, tell me</Caps>
            <Title size={42} style={{ display: 'block', marginTop: 6 }}>
              what should I<br />
              call you?
            </Title>
          </div>
          <div style={{ position: 'absolute', top: 540, left: 28, right: 28 }}>
            <input
              autoFocus
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && proceed()}
              placeholder="your name"
              style={{
                width: '100%', background: 'transparent', border: 'none', outline: 'none',
                color: PHOTO.bone, fontFamily: serif, fontStyle: 'italic', fontSize: 42,
                borderBottom: `1px solid ${PHOTO.hairlineStrong}`, padding: '0 0 12px',
              }}
            />
          </div>
          <div style={{ position: 'absolute', bottom: 80, left: 28, right: 28 }}>
            <button onClick={proceed} disabled={!name.trim()} style={{
              width: '100%', background: name.trim() ? PHOTO.bone : 'rgba(220,200,170,0.2)',
              color: PHOTO.night, borderRadius: 999, border: 'none',
              padding: '17px 0', fontSize: 15, fontWeight: 600,
              cursor: name.trim() ? 'pointer' : 'not-allowed',
              fontFamily: sans, opacity: name.trim() ? 1 : 0.5,
              boxShadow: name.trim() ? `0 8px 28px rgba(0,0,0,0.5), 0 0 60px ${PHOTO.amberGlow}` : 'none',
            }}>{hasGiftInUrl ? 'Open my bouquet' : 'Into the garden'}</button>
          </div>
        </>
      )}

      <HomeIndicator />
    </Screen>
  );
};

// ── Settings (long-press logo or via menu) ──────────────────
const AppSettings = ({ state, actions, go }) => {
  const [confirming, setConfirming] = React.useState(false);
  return (
    <Screen>
      <PhotoBackdrop warmth={0.7} />
      <StatusBar />
      <NavHeader left={<span onClick={() => go('home')} style={{ cursor: 'pointer' }}>←</span>} center="Settings" />

      <div style={{ position: 'absolute', top: 110, left: 24, right: 24 }}>
        <Title size={36}>About this garden.</Title>
      </div>

      <div style={{ position: 'absolute', top: 220, left: 16, right: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Glass style={{ padding: 16, borderRadius: 16 }}>
          <Caps size={9}>you are</Caps>
          <div style={{ fontFamily: serif, fontStyle: 'italic', fontSize: 22, marginTop: 4 }}>
            {(state.user && state.user.name) || '—'}
          </div>
        </Glass>
        <Glass style={{ padding: 16, borderRadius: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Caps size={9}>active bouquets</Caps>
            <div style={{ fontFamily: serif, fontStyle: 'italic', fontSize: 20, marginTop: 2 }}>
              {state.bouquets.length}
            </div>
          </div>
          <div>
            <Caps size={9}>pressed</Caps>
            <div style={{ fontFamily: serif, fontStyle: 'italic', fontSize: 20, marginTop: 2 }}>
              {state.pressed.length}
            </div>
          </div>
        </Glass>
      </div>

      <div style={{ position: 'absolute', bottom: 90, left: 16, right: 16 }}>
        {!confirming ? (
          <button onClick={() => setConfirming(true)} style={{
            width: '100%', background: 'transparent', color: PHOTO.rose,
            border: `1px solid ${PHOTO.rose}`, borderRadius: 999, padding: '12px 0',
            fontSize: 13, cursor: 'pointer', fontFamily: sans, opacity: 0.7,
          }}>reset the garden</button>
        ) : (
          <Glass style={{ padding: 14, borderRadius: 14 }}>
            <div style={{ fontFamily: serif, fontStyle: 'italic', fontSize: 14, color: PHOTO.bone, textAlign: 'center', marginBottom: 10 }}>
              Erase every bouquet and pressed page?<br />There is no coming back.
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => { actions.reset(); window.location.reload(); }} style={{
                flex: 1, background: PHOTO.rose, color: PHOTO.bone, border: 'none',
                borderRadius: 999, padding: '12px 0', fontSize: 13, cursor: 'pointer', fontFamily: sans,
              }}>yes, erase</button>
              <button onClick={() => setConfirming(false)} style={{
                flex: 1, background: 'transparent', color: PHOTO.boneDim,
                border: `1px solid ${PHOTO.hairlineStrong}`, borderRadius: 999, padding: '12px 0',
                fontSize: 13, cursor: 'pointer', fontFamily: sans,
              }}>keep them</button>
            </div>
          </Glass>
        )}
      </div>

      <HomeIndicator />
    </Screen>
  );
};

// ── Scale-to-fit frame ──────────────────────────────────────
const W = 390, H = 844;

const PhoneFrame = ({ children }) => {
  const [scale, setScale] = React.useState(1);
  const [isMobile, setIsMobile] = React.useState(false);

  React.useEffect(() => {
    const update = () => {
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      const sx = vw / W;
      const sy = vh / H;
      const mobile = vw < 600;
      setIsMobile(mobile);
      // On mobile: scale to fill (allow > 1). On desktop: cap at 1 to keep phone-frame look.
      const s = mobile ? Math.min(sx, sy) : Math.min(sx, sy, 1);
      setScale(s);
    };
    update();
    window.addEventListener('resize', update);
    window.addEventListener('orientationchange', update);
    return () => {
      window.removeEventListener('resize', update);
      window.removeEventListener('orientationchange', update);
    };
  }, []);

  return (
    <div style={{
      width: '100vw', height: '100dvh', overflow: 'hidden',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: PHOTO.night,
    }}>
      <div style={{
        width: W, height: H,
        transform: `scale(${scale})`, transformOrigin: 'center center',
        position: 'relative',
        borderRadius: isMobile ? 0 : 44,
        overflow: 'hidden',
        boxShadow: isMobile ? 'none' : '0 30px 80px rgba(0,0,0,0.6), 0 0 0 8px #1a1714, 0 0 0 9px #2a2218',
      }}>
        {children}
      </div>
    </div>
  );
};

// ── Root router ─────────────────────────────────────────────
const App = () => {
  const [state, actions] = usePosyState();
  const [screen, setScreen] = React.useState('home');
  const [selectedPressedId, setSelectedPressedId] = React.useState(null);
  const [pendingBouquet, setPendingBouquet] = React.useState(null);
  const [bootDone, setBootDone] = React.useState(false);
  const [giftError, setGiftError] = React.useState(false);

  // On mount: read URL params, decide initial flow
  React.useEffect(() => {
    const params = readUrlParams();

    if (params.gift) {
      const decoded = decodeBouquetFromShare(params.gift);
      if (decoded) {
        const newB = actions.addBouquet({
          from: decoded.from,
          to: decoded.to,
          note: decoded.note,
          stems: decoded.stems,
          sentAt: decoded.sentAt,
          receivedAt: Date.now(),
          unwrapped: false,
        });
        setPendingBouquet(newB);
        clearUrlParams();
      } else {
        setGiftError(true);
        clearUrlParams();
      }
    } else if (params.send) {
      if (state.user) {
        setScreen('compose');
      }
      clearUrlParams();
    }

    setBootDone(true);
    // eslint-disable-next-line
  }, []);

  // If a pending bouquet exists, show unwrap
  if (pendingBouquet) {
    return (
      <PhoneFrame>
        <AppUnbox bouquet={pendingBouquet} onDone={() => {
          actions.markUnwrapped(pendingBouquet.id);
          setPendingBouquet(null);
          setScreen('home');
        }} />
      </PhoneFrame>
    );
  }

  // Onboarding (no user yet)
  if (!state.user) {
    return (
      <PhoneFrame>
        <AppOnboarding
          hasGiftInUrl={!!readUrlParams().gift}
          onComplete={(user) => actions.setUser(user)}
        />
      </PhoneFrame>
    );
  }

  if (!bootDone) {
    return (
      <PhoneFrame>
        <Screen><PhotoBackdrop /></Screen>
      </PhoneFrame>
    );
  }

  const go = (id) => setScreen(id);

  let content;
  switch (screen) {
    case 'home':    content = <AppVase    state={state} actions={actions} go={go} />; break;
    case 'care':    content = <AppCare    state={state} actions={actions} go={go} />; break;
    case 'detail':  content = <AppDetail  state={state} actions={actions} go={go} />; break;
    case 'book':    content = <AppBook    state={state} actions={actions} go={go} setSelectedPressedId={setSelectedPressedId} />; break;
    case 'page':    content = <AppPage    state={state} actions={actions} go={go} selectedPressedId={selectedPressedId} setSelectedPressedId={setSelectedPressedId} />; break;
    case 'compose': content = <AppCompose state={state} actions={actions} go={go} />; break;
    case 'settings':content = <AppSettings state={state} actions={actions} go={go} />; break;
    default:        content = <AppVase    state={state} actions={actions} go={go} />;
  }

  const giftBanner = giftError ? (
    <div style={{
      position: 'absolute', top: 50, left: 16, right: 16, zIndex: 100,
      background: 'rgba(168,108,95,0.94)', color: PHOTO.bone,
      borderRadius: 14, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
      boxShadow: '0 8px 24px rgba(0,0,0,0.5)',
      backdropFilter: 'blur(8px)',
    }}>
      <div style={{ flex: 1, fontFamily: serif, fontStyle: 'italic', fontSize: 14, lineHeight: 1.3 }}>
        That link couldn't be opened.<br />
        <span style={{ fontSize: 12, opacity: 0.85 }}>Ask them to send a fresh one.</span>
      </div>
      <span onClick={() => setGiftError(false)} style={{ cursor: 'pointer', fontSize: 18, opacity: 0.8, padding: '0 6px' }}>×</span>
    </div>
  ) : null;

  return <PhoneFrame>{content}{giftBanner}</PhoneFrame>;
};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
