// Dateora — in-app screens: AppShell (sidebar), Conversation, History, Account

// ─── AppShell with sidebar nav ───────────────────────────────────
const AppShell = ({ t, currentView, onNav, onLogout, children }) => {
  const items = [
    { id: 'conversation', label: 'Session', icon: <Icon.chat /> },
    { id: 'history', label: 'History', icon: <Icon.history /> },
    { id: 'account', label: 'Account', icon: <Icon.user /> },
  ];
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', background: t.bg }}>
      <aside style={{
        width: 220, flexShrink: 0, padding: '24px 16px 20px',
        borderRight: '1px solid ' + t.border,
        display: 'flex', flexDirection: 'column',
        background: t.id === 'editorial' ? t.surface2 : 'transparent',
      }}>
        <div style={{ padding: '4px 8px 28px' }}><Wordmark t={t} size={15} /></div>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1 }}>
          {items.map((it) => {
            const active = it.id === currentView;
            return (
              <button key={it.id} onClick={() => onNav(it.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '10px 12px', borderRadius: t.radiusLg,
                  border: 'none', background: active ? (t.id === 'editorial' ? t.surface : t.surface2) : 'transparent',
                  color: active ? t.ink : t.muted,
                  cursor: 'pointer', fontSize: 14, fontFamily: t.fontBody, fontWeight: 500,
                  textAlign: 'left', transition: 'all .15s',
                  borderLeft: t.id === 'editorial' && active ? '2px solid ' + t.accent : '2px solid transparent',
                }}>
                {it.icon} {it.label}
                {it.id === 'conversation' && active && (
                  <span style={{ marginLeft: 'auto', width: 6, height: 6, borderRadius: 3, background: t.accent, animation: 'dateora-pulse 1.4s infinite' }}></span>
                )}
              </button>
            );
          })}
        </nav>
        <div style={{ padding: '16px 12px 8px', borderTop: '1px solid ' + t.border, marginTop: 12 }}>
          <div style={{ fontSize: 12, color: t.muted, marginBottom: 8 }}>Trial · 12 days left</div>
          <div style={{ height: 4, borderRadius: 2, background: t.border, overflow: 'hidden', marginBottom: 16 }}>
            <div style={{ width: '15%', height: '100%', background: t.accent }}></div>
          </div>
          <button onClick={onLogout} style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '6px 8px',
            border: 'none', background: 'transparent', color: t.subtle,
            fontSize: 13, fontFamily: t.fontBody, cursor: 'pointer', width: '100%', textAlign: 'left',
          }}><Icon.logout /> Sign out</button>
        </div>
      </aside>
      <main style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>{children}</main>
    </div>
  );
};

// ─── Conversation screen — the heart ───────────────────────────
const QUICK_REPLIES = [
  "I went blank again",
  "Give me a real opener",
  "What should I have said?",
  "She walked off",
  "I rehearsed and it worked",
];

const ConversationScreen = ({ t, messages, onSend, sending }) => {
  const [draft, setDraft] = React.useState('');
  const transcriptRef = React.useRef(null);
  React.useEffect(() => {
    const el = transcriptRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages, sending]);
  const send = () => {
    const v = draft.trim();
    if (!v || sending) return;
    onSend(v);
    setDraft('');
  };
  // Show 3 rotating chips only when the last message was the coach's
  const lastIsCoach = messages.length > 0 && messages[messages.length - 1].role === 'coach';
  const sugg = lastIsCoach ? QUICK_REPLIES.slice(0, 3) : [];

  // Layout differs by direction. Mentor: full-bleed avatar with overlay UI.
  // Editorial: 2-column with portrait card. Studio: split layout.
  return (
    <div style={{ width: '100%', height: '100%', position: 'relative', display: 'flex', flexDirection: 'column', background: t.bg }}>
      <ConversationHeader t={t} />
      <div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>
        <ConversationStage t={t} messages={messages} sending={sending} transcriptRef={transcriptRef} />
      </div>
      <ConversationInputBar t={t} draft={draft} setDraft={setDraft} send={send} sending={sending} suggestions={sugg} />
    </div>
  );
};

const ConversationHeader = ({ t }) => (
  <div style={{
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '14px 24px', borderBottom: '1px solid ' + t.border, flexShrink: 0,
  }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{
        width: 32, height: 32, borderRadius: '50%', overflow: 'hidden', position: 'relative',
        border: '1px solid ' + t.border,
      }}>
        <AvatarPortrait t={t} />
      </div>
      <div>
        <div style={{ fontSize: 14, fontWeight: 600, color: t.ink, fontFamily: t.fontBody }}>Adam · {t.coachRole}</div>
        <div style={{ fontSize: 11, color: t.muted, display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: t.success, animation: 'dateora-pulse 1.4s infinite' }}></span>
          Live · session 04 · 06:18
        </div>
      </div>
    </div>
    <div style={{ display: 'flex', gap: 8 }}>
      <Btn t={t} variant="ghost" size="sm">Save reps</Btn>
      <Btn t={t} variant="secondary" size="sm">End session</Btn>
    </div>
  </div>
);

const ConversationStage = ({ t, messages, sending, transcriptRef }) => {
  if (t.id === 'mentor') {
    // Full-bleed avatar with transcript floating bottom-right
    return (
      <div style={{ width: '100%', height: '100%', position: 'relative' }}>
        <AvatarPortrait t={t} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, transparent 0%, transparent 30%, rgba(20,17,15,0.4) 60%, rgba(20,17,15,0.85) 100%)' }}></div>
        <div ref={transcriptRef} style={{
          position: 'absolute', right: 24, top: 24, bottom: 24, width: 380,
          background: 'rgba(20,17,15,0.65)', backdropFilter: 'blur(24px)',
          border: '1px solid ' + t.border, borderRadius: t.radiusLg,
          padding: '20px 18px', overflow: 'auto',
          display: 'flex', flexDirection: 'column', gap: 14,
        }}>
          {messages.map((m, i) => <Bubble key={i} t={t} m={m} />)}
          {sending && <TypingIndicator t={t} />}
        </div>
        <div style={{ position: 'absolute', left: 32, bottom: 32, maxWidth: 360 }}>
          <Eyebrow t={t} style={{ color: 'rgba(244,237,227,0.6)', marginBottom: 12 }}>Now rehearsing</Eyebrow>
          <Display t={t} size={32} style={{ color: t.ink }}>The approach: 30 seconds, no script.</Display>
        </div>
      </div>
    );
  }

  if (t.id === 'editorial') {
    return (
      <div style={{ width: '100%', height: '100%', display: 'grid', gridTemplateColumns: '380px 1fr' }}>
        <div style={{ position: 'relative', borderRight: '1px solid ' + t.borderStrong, padding: 24, display: 'flex', flexDirection: 'column' }}>
          <div style={{ aspectRatio: '3/4', position: 'relative', overflow: 'hidden', marginBottom: 16, border: '1px solid ' + t.borderStrong }}>
            <AvatarPortrait t={t} />
          </div>
          <div style={{ fontSize: 12, color: t.muted, fontFamily: t.fontBody, letterSpacing: '0.06em', marginBottom: 6 }}>SESSION 04 · IN PROGRESS</div>
          <Display t={t} size={32} style={{ marginBottom: 10 }}>The approach</Display>
          <p style={{ fontSize: 14, color: t.muted, lineHeight: 1.55, fontFamily: t.fontBody }}>
            Today, we rehearse the first 30 seconds. Less than the time it takes to forget what you wanted to say.
          </p>
          <div style={{ marginTop: 'auto', paddingTop: 20, borderTop: '1px solid ' + t.border, fontSize: 12, color: t.subtle, fontStyle: 'italic', fontFamily: t.fontDisplay }}>
            Continued from p. 23
          </div>
        </div>
        <div ref={transcriptRef} style={{ padding: '24px 56px', overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 18 }}>
          {messages.map((m, i) => <Bubble key={i} t={t} m={m} />)}
          {sending && <TypingIndicator t={t} />}
        </div>
      </div>
    );
  }

  // studio
  return (
    <div style={{ width: '100%', height: '100%', display: 'grid', gridTemplateColumns: '1fr 1.1fr' }}>
      <div style={{ position: 'relative', padding: 24 }}>
        <div style={{
          width: '100%', height: '100%', borderRadius: t.radiusXl, overflow: 'hidden', position: 'relative',
          border: '1px solid ' + t.border, background: t.surface,
        }}>
          <AvatarPortrait t={t} />
          <div style={{ position: 'absolute', top: 16, left: 16, display: 'flex', alignItems: 'center', gap: 6, padding: '5px 10px', borderRadius: 100, background: 'rgba(10,10,11,0.6)', backdropFilter: 'blur(10px)', fontSize: 11, fontFamily: t.fontMono, color: t.ink }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: '#FF5A36', animation: 'dateora-pulse 1.2s infinite' }}></span>
            LIVE
          </div>
          <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', gap: 8 }}>
              <PillBtn t={t} active><Icon.chat /> Text</PillBtn>
              <PillBtn t={t}><Icon.mic /> Voice</PillBtn>
            </div>
            <div style={{ display: 'flex', gap: 4 }}>
              {[3, 7, 12, 18, 14, 9, 5, 11, 15, 8].map((h, i) => (
                <div key={i} style={{ width: 3, height: h, borderRadius: 1.5, background: t.accent, opacity: 0.4 + (i / 20), animation: `dateora-wave 1.2s ${i * 0.1}s infinite ease-in-out` }}></div>
              ))}
            </div>
          </div>
        </div>
      </div>
      <div ref={transcriptRef} style={{ padding: '24px 32px 24px 12px', overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 11, color: t.subtle, fontFamily: t.fontMono, letterSpacing: '0.08em', marginBottom: 4 }}>
          SESSION 04 · APPROACH DRILLS · 06:18
        </div>
        {messages.map((m, i) => <Bubble key={i} t={t} m={m} />)}
        {sending && <TypingIndicator t={t} />}
      </div>
    </div>
  );
};

const PillBtn = ({ t, children, active }) => (
  <button style={{
    padding: '6px 12px', borderRadius: 100, fontSize: 12, fontFamily: t.fontMono,
    border: '1px solid ' + (active ? t.accent : 'rgba(255,255,255,0.15)'),
    background: active ? t.accentSoft : 'rgba(10,10,11,0.5)',
    color: active ? t.accent : t.ink,
    cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, backdropFilter: 'blur(10px)',
  }}>{children}</button>
);

const Bubble = ({ t, m }) => {
  const isCoach = m.role === 'coach';
  if (t.id === 'editorial') {
    return (
      <div>
        <div style={{
          fontSize: 11, color: t.muted, fontFamily: t.fontBody,
          letterSpacing: '0.08em', marginBottom: 6,
        }}>{isCoach ? 'ADAM' : 'YOU'}</div>
        <div style={{
          fontSize: isCoach ? 19 : 16, lineHeight: 1.5,
          color: t.ink,
          fontFamily: isCoach ? t.fontDisplay : t.fontBody,
          fontStyle: isCoach ? 'italic' : 'normal',
          maxWidth: 580,
        }}>{m.text}</div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', justifyContent: isCoach ? 'flex-start' : 'flex-end' }}>
      <div style={{
        maxWidth: '85%',
        padding: '12px 16px',
        borderRadius: t.radiusLg,
        background: isCoach ? t.surface2 : t.accent,
        color: isCoach ? t.ink : t.accentInk,
        fontSize: 14, lineHeight: 1.55, fontFamily: t.fontBody,
        border: isCoach ? '1px solid ' + t.border : 'none',
        whiteSpace: 'pre-wrap',
      }}>{m.text}</div>
    </div>
  );
};

const TypingIndicator = ({ t }) => (
  <div style={{
    alignSelf: 'flex-start',
    display: 'inline-flex', gap: 4, padding: '12px 16px',
    background: t.surface2, borderRadius: t.radiusLg,
    border: '1px solid ' + t.border,
  }}>
    {[0, 1, 2].map((i) => (
      <span key={i} style={{
        width: 6, height: 6, borderRadius: 3, background: t.muted,
        animation: `dateora-bounce 1.2s ${i * 0.15}s infinite ease-in-out`,
      }}></span>
    ))}
  </div>
);

const ConversationInputBar = ({ t, draft, setDraft, send, sending, suggestions = [] }) => (
  <div style={{
    flexShrink: 0, padding: '14px 24px',
    borderTop: '1px solid ' + t.border,
    background: t.id === 'mentor' ? 'rgba(20,17,15,0.6)' : t.bg,
    backdropFilter: 'blur(20px)',
  }}>
    {suggestions.length > 0 && !sending && !draft && (
      <div style={{ display: 'flex', gap: 8, maxWidth: 880, margin: '0 auto 10px', flexWrap: 'wrap' }}>
        {suggestions.map((s) => (
          <button key={s} onClick={() => setDraft(s)} style={{
            padding: '6px 12px', borderRadius: 100, fontSize: 12,
            fontFamily: t.fontBody, fontWeight: 500,
            border: '1px solid ' + t.border,
            background: t.surface, color: t.muted,
            cursor: 'pointer', whiteSpace: 'nowrap',
            transition: 'all .15s',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.color = t.ink; e.currentTarget.style.borderColor = t.borderStrong; }}
          onMouseLeave={(e) => { e.currentTarget.style.color = t.muted; e.currentTarget.style.borderColor = t.border; }}>
            {s}
          </button>
        ))}
      </div>
    )}
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      background: t.surface, border: '1px solid ' + t.border,
      borderRadius: t.radiusXl, padding: '6px 6px 6px 18px',
      maxWidth: 880, margin: '0 auto',
    }}>
      <button style={{
        border: 'none', background: 'transparent', color: t.muted, cursor: 'pointer',
        padding: 8, display: 'flex', alignItems: 'center',
      }}><Icon.mic /></button>
      <input
        value={draft}
        onChange={(e) => setDraft(e.target.value)}
        onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        placeholder={sending ? 'Adam is thinking…' : "Type your response, or describe a real moment"}
        disabled={sending}
        style={{
          flex: 1, border: 'none', outline: 'none',
          background: 'transparent', color: t.ink,
          fontSize: 15, fontFamily: t.fontBody, padding: '10px 0',
        }}
      />
      <button onClick={send} disabled={sending || !draft.trim()} style={{
        border: 'none',
        background: draft.trim() && !sending ? t.accent : t.surface2,
        color: draft.trim() && !sending ? t.accentInk : t.muted,
        cursor: draft.trim() && !sending ? 'pointer' : 'default',
        width: 40, height: 40, borderRadius: t.radiusLg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'background .15s',
      }}><Icon.send /></button>
    </div>
    <div style={{ fontSize: 11, color: t.subtle, textAlign: 'center', marginTop: 8 }}>
      Adam can be wrong. Don't use Dateora for crisis support — see help &amp; resources.
    </div>
  </div>
);

// ─── History ─────────────────────────────────────────────────
const HistoryScreen = ({ t, sessions, onDelete, onOpen }) => (
  <div style={{ width: '100%', height: '100%', overflow: 'auto', padding: '36px 56px' }}>
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Eyebrow t={t} style={{ marginBottom: 12 }}>Your reps</Eyebrow>
      <Display t={t} size={t.id === 'editorial' ? 56 : 36} style={{ marginBottom: 8 }}>History</Display>
      <p style={{ color: t.muted, fontSize: 15, lineHeight: 1.5, marginBottom: 32 }}>
        Past sessions with Adam. Reopen to continue, or delete — gone for good.
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: t.id === 'editorial' ? 0 : 8 }}>
        {sessions.map((s, i) => (
          <SessionRow key={s.id} t={t} session={s} onDelete={() => onDelete(s.id)} onOpen={() => onOpen(s.id)} first={i === 0} />
        ))}
      </div>
    </div>
  </div>
);

const SessionRow = ({ t, session, onDelete, onOpen, first }) => {
  const [hover, setHover] = React.useState(false);
  if (t.id === 'editorial') {
    return (
      <article
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: 24, alignItems: 'baseline',
          padding: '24px 0', borderTop: first ? '1px solid ' + t.borderStrong : 'none',
          borderBottom: '1px solid ' + t.border, cursor: 'pointer',
        }}
        onClick={onOpen}>
        <div style={{ fontFamily: t.fontDisplay, fontSize: 42, color: t.accent, lineHeight: 1 }}>{String(session.idx).padStart(2, '0')}</div>
        <div>
          <div style={{ fontFamily: t.fontDisplay, fontSize: 24, lineHeight: 1.2, marginBottom: 6, color: t.ink }}>{session.title}</div>
          <div style={{ fontSize: 13, color: t.muted, fontFamily: t.fontBody, marginBottom: 8 }}>
            {session.when} · {session.minutes} min · {session.reps} reps
          </div>
          <p style={{ fontSize: 14, color: t.muted, fontStyle: 'italic', fontFamily: t.fontDisplay, fontSize: 16 }}>
            &ldquo;{session.snippet}&rdquo;
          </p>
        </div>
        <button onClick={(e) => { e.stopPropagation(); onDelete(); }}
          style={{ opacity: hover ? 1 : 0.3, border: 'none', background: 'transparent', color: t.muted, cursor: 'pointer', padding: 8, transition: 'opacity .15s' }}>
          <Icon.trash />
        </button>
      </article>
    );
  }
  return (
    <div
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={onOpen}
      style={{
        padding: '16px 18px', borderRadius: t.radiusLg,
        background: hover ? t.surface : 'transparent',
        border: '1px solid ' + (hover ? t.border : 'transparent'),
        display: 'flex', alignItems: 'center', gap: 16, cursor: 'pointer',
        transition: 'all .15s',
      }}>
      <div style={{
        width: 42, height: 42, borderRadius: t.id === 'studio' ? t.radiusLg : '50%',
        background: t.accentSoft, color: t.accent, fontFamily: t.fontMono, fontWeight: 600,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 13,
      }}>{String(session.idx).padStart(2, '0')}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: t.ink, marginBottom: 4, fontFamily: t.fontBody }}>{session.title}</div>
        <div style={{ fontSize: 12, color: t.muted, display: 'flex', gap: 12 }}>
          <span>{session.when}</span>
          <span>·</span>
          <span>{session.minutes} min</span>
          <span>·</span>
          <span>{session.reps} reps</span>
        </div>
      </div>
      <div style={{ fontSize: 13, color: t.muted, maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontStyle: 'italic' }}>
        "{session.snippet}"
      </div>
      <button onClick={(e) => { e.stopPropagation(); onDelete(); }}
        style={{
          opacity: hover ? 1 : 0, border: '1px solid ' + t.border, background: 'transparent',
          color: t.muted, cursor: 'pointer', padding: 8, borderRadius: t.radius,
          transition: 'opacity .15s', display: 'flex', alignItems: 'center',
        }}>
        <Icon.trash />
      </button>
    </div>
  );
};

// ─── Account ─────────────────────────────────────────────────
const AccountScreen = ({ t, email }) => {
  return (
    <div style={{ width: '100%', height: '100%', overflow: 'auto', padding: '36px 56px' }}>
      <div style={{ maxWidth: 720, margin: '0 auto' }}>
        <Eyebrow t={t} style={{ marginBottom: 12 }}>Settings</Eyebrow>
        <Display t={t} size={t.id === 'editorial' ? 56 : 36} style={{ marginBottom: 32 }}>Account</Display>
        <Section t={t} title="Profile">
          <Row t={t} label="Email" value={email || 'you@example.com'} action="Change" />
          <Row t={t} label="Password" value="Last changed 2 weeks ago" action="Reset" />
          <Row t={t} label="Display name" value="—" action="Add" />
        </Section>
        <Section t={t} title="Subscription">
          <Row t={t} label="Plan" value="Dateora · Unlimited" action="Manage" />
          <Row t={t} label="Trial" value={(<span style={{ color: t.success }}>12 days remaining</span>)} />
          <Row t={t} label="First charge" value="May 28, 2026 · $24.00" action="Cancel" actionDanger />
          <Row t={t} label="Payment method" value="•••• 4242 · expires 12/28" action="Update" />
        </Section>
        <Section t={t} title="Data">
          <Row t={t} label="Conversation history" value="12 sessions saved" action="Download" />
          <Row t={t} label="Delete account" value="Erase everything, permanently" action="Delete" actionDanger />
        </Section>
        <div style={{ marginTop: 32, padding: 20, background: t.surface, borderRadius: t.radiusLg, border: '1px solid ' + t.border, fontSize: 13, color: t.muted, lineHeight: 1.55 }}>
          <div style={{ color: t.ink, fontWeight: 600, marginBottom: 4 }}>Need help?</div>
          Reply to any Dateora email — a person reads them. Or write us at support@dateora.com.
        </div>
      </div>
    </div>
  );
};

const Section = ({ t, title, children }) => (
  <section style={{ marginBottom: 36 }}>
    <div style={{
      fontSize: 12, color: t.muted, marginBottom: 12,
      letterSpacing: '0.12em', textTransform: 'uppercase',
      fontFamily: t.id === 'studio' ? t.fontMono : t.fontBody, fontWeight: 600,
    }}>{title}</div>
    <div style={{ background: t.surface, border: '1px solid ' + t.border, borderRadius: t.radiusLg, overflow: 'hidden' }}>
      {children}
    </div>
  </section>
);

const Row = ({ t, label, value, action, actionDanger }) => (
  <div style={{
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '14px 18px', borderBottom: '1px solid ' + t.border,
  }}>
    <div>
      <div style={{ fontSize: 13, color: t.muted, marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 14, color: t.ink, fontFamily: t.fontBody }}>{value}</div>
    </div>
    {action && (
      <button style={{
        border: 'none', background: 'transparent',
        color: actionDanger ? t.danger : t.accent,
        fontSize: 13, fontFamily: t.fontBody, fontWeight: 500, cursor: 'pointer',
        padding: '6px 10px', borderRadius: t.radius,
      }}>{action}</button>
    )}
  </div>
);

Object.assign(window, { AppShell, ConversationScreen, HistoryScreen, AccountScreen, Bubble, TypingIndicator });
