// Agentic Title — shared page shell for chat-style nav pages.
// Loads after home-parts.jsx (uses window.Sidebar + window.TopBar).
// Each page renders:  <AgenticPage title subtitle active chips> ...thread... </AgenticPage>

function AgenticAvatar() {
  return (
    <span style={{ width: 44, height: 44, flex: 'none', borderRadius: '999px', background: '#0E0D0C', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
      <img src="/assets/mark-orange.png" alt="" style={{ width: 24, height: 'auto', display: 'block' }} />
    </span>
  );
}

// Athena — the intelligence native to the platform, not a bolted-on chatbot.
// Her mark sits on the same warm paper as the page (no dark widget bubble),
// rests static, and animates only while she is thinking.
function AthenaAvatar({ thinking = false, size = 34 }) {
  return (
    <span style={{
      width: size, height: size, flex: 'none',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      position: 'relative',
    }}>
      {thinking ? (
        <video src="/assets/athena-thinking.mp4" autoPlay loop muted playsInline
          style={{ width: size, height: size, objectFit: 'cover', borderRadius: '999px', mixBlendMode: 'multiply', display: 'block' }} />
      ) : (
        <img src="/assets/athena-glyph.png" alt="Athena" style={{ width: size, height: 'auto', display: 'block' }} />
      )}
    </span>
  );
}

// Agent message bubble (white card). Pass `tone="cognac"` for the dark-red emphasis bubble.
function AgenticMessage({ tone = 'plain', label, noAvatar = false, indent = false, children, style = {} }) {
  const cognac = tone === 'cognac';
  return (
    <section className="at-msg" style={{ display: 'flex', gap: 18, alignItems: 'flex-start', ...style }}>
      {!noAvatar && <AthenaAvatar />}
      {noAvatar && indent && <span aria-hidden="true" style={{ width: 34, flex: 'none' }} />}
      <div style={{
        flex: 1,
        background: cognac ? 'var(--at-cognac)' : '#FBFAF8',
        border: cognac ? '1px solid transparent' : '1px solid var(--border-hairline)',
        borderRadius: 'var(--radius-lg)', borderTopLeftRadius: 'var(--radius-xs)',
        padding: cognac ? '34px 40px' : '28px 34px',
        boxShadow: cognac ? 'var(--shadow-md)' : 'var(--shadow-sm)',
      }}>
        {label && <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--at-hermes)', marginBottom: 14 }}>{label}</div>}
        <div style={{ fontFamily: 'var(--font-serif)', fontSize: 19, lineHeight: 1.5, color: cognac ? 'var(--at-cream)' : 'var(--text-primary)' }}>{children}</div>
      </div>
    </section>
  );
}

// Intro block: avatar + eyebrow label, big serif-italic headline, optional orange subline.
function AgenticIntro({ label, headline, subline, style = {} }) {
  return (
    <section className="at-msg" style={style}>
      <div style={{ marginBottom: 20 }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.14em', color: 'var(--at-hermes)' }}>{label}</span>
      </div>
      <h1 style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 500, fontSize: 'clamp(28px, 3.6vw, 42px)', lineHeight: 1.1, color: 'var(--text-primary)', textTransform: 'none', margin: 0 }}>{headline}</h1>
      {subline && <p style={{ fontFamily: 'var(--font-serif)', fontSize: 'clamp(17px, 1.9vw, 21px)', lineHeight: 1.45, color: '#B05A2C', margin: '20px 0 0', maxWidth: 920 }}>{subline}</p>}
    </section>
  );
}

// ---- Conversation state ----------------------------------------------------
// Reads ONLY from window.AT_ANSWERS (answers.js). Chips + composer call ask().
// No free generation: an unmatched question returns the human-handoff fallback.
function useATChat() {
  const [messages, setMessages] = React.useState([]);
  const [pending, setPending] = React.useState(false);
  const ask = React.useCallback((text) => {
    const q = (text || '').trim();
    if (!q) return;
    setMessages((m) => [...m, { from: 'user', text: q }]);
    setPending(true);
    setTimeout(() => {
      const item = (window.ATLookup && window.ATLookup(q)) || null;
      const reply = item
        ? { from: 'agent', text: item.a, draft: item.status !== 'approved', disclaimer: true, action: item.action }
        : { from: 'agent', text: window.AT_ANSWERS.fallback, handoff: true };
      setMessages((m) => [...m, reply]);
      setPending(false);
    }, 750);
  }, []);
  const say = React.useCallback((text, opts) => {
    if (!text) return;
    setMessages((m) => [...m, { from: 'agent', text, draft: !!(opts && opts.draft) }]);
  }, []);
  const reset = React.useCallback(() => { setMessages([]); setPending(false); }, []);
  // "New Conversation" (sidebar) clears the thread on whatever page is showing.
  React.useEffect(() => {
    const onNew = () => reset();
    window.addEventListener('at-new-conversation', onNew);
    return () => window.removeEventListener('at-new-conversation', onNew);
  }, [reset]);
  return { messages, pending, ask, say, reset };
}

// User message bubble (ink, right-aligned).
function ATUserBubble({ text }) {
  return (
    <section className="at-msg" style={{ display: 'flex', justifyContent: 'flex-end' }}>
      <div style={{
        maxWidth: '78%', background: 'var(--at-ink)', color: 'var(--at-cream)',
        borderRadius: 'var(--radius-lg)', borderTopRightRadius: 'var(--radius-xs)',
        padding: '16px 22px', fontFamily: 'var(--font-serif)', fontSize: 18, lineHeight: 1.45,
        boxShadow: 'var(--shadow-sm)',
      }}>{text}</div>
    </section>
  );
}

// Agent answer bubble. Draft answers get an amber ribbon + dashed border so
// unreviewed copy can never ship silently.
function ATAnswerBubble({ text, draft, handoff, disclaimer, action }) {
  return (
    <section className="at-msg" style={{ display: 'flex', gap: 18, alignItems: 'flex-start' }}>
      <AthenaAvatar />
      <div style={{ flex: 1 }}>
        {draft && (
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 10,
            background: '#FBEAD8', color: '#9A5212', border: '1px solid #E6B98A',
            borderRadius: 'var(--radius-pill)', padding: '5px 12px',
            fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '999px', background: '#C8781E' }} />
            Draft · Pending compliance review
          </div>
        )}
        <div style={{
          background: '#FBFAF8',
          border: draft ? '1px dashed #E0B488' : '1px solid var(--border-hairline)',
          borderRadius: 'var(--radius-lg)', borderTopLeftRadius: 'var(--radius-xs)',
          padding: '24px 30px', boxShadow: 'var(--shadow-sm)',
        }}>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 18, lineHeight: 1.5, color: 'var(--text-primary)', whiteSpace: 'pre-wrap' }}>{text}</div>
          {action === 'order' && (
            <button onClick={() => window.ATOpenOrder()} style={{
              marginTop: 16, cursor: 'pointer', border: 'none', background: 'var(--at-hermes)', color: '#1c0d04',
              borderRadius: 'var(--radius-md)', padding: '12px 20px', fontFamily: 'var(--font-mono)', fontWeight: 500,
              fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase',
            }}>Open an Order →</button>
          )}
          {(disclaimer || handoff) && (
            <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--border-hairline)', fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '0.06em', color: 'var(--text-muted)', lineHeight: 1.5 }}>
              {window.AT_ANSWERS.disclaimer}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// Renders the appended conversation + a typing indicator; auto-scrolls its thread.
function ATMessages({ messages, pending }) {
  const anchor = React.useRef(null);
  React.useEffect(() => {
    if (!messages.length && !pending) return;
    const a = anchor.current;
    if (!a) return;
    const thread = a.closest('.at-thread');
    if (thread) thread.scrollTop = thread.scrollHeight;
  }, [messages.length, pending]);
  if (!messages.length && !pending) return <div ref={anchor} />;
  return (
    <React.Fragment>
      {messages.map((m, i) => m.from === 'user'
        ? <ATUserBubble key={i} text={m.text} />
        : <ATAnswerBubble key={i} {...m} />)}
      {pending && (
        <section style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
          <AthenaAvatar thinking />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Athena is thinking…</span>
        </section>
      )}
      <div ref={anchor} />
    </React.Fragment>
  );
}

// Chip row — each chip asks its question.
function ATChipRow({ chips = [], onAsk }) {
  if (!chips.length) return null;
  return (
    <div className="at-chips" style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginBottom: 16 }}>
      {chips.map((c) => (
        <button key={c} onClick={() => onAsk(c)} style={{
          cursor: 'pointer', background: '#FBFAF8', border: '1px solid var(--border-default)',
          borderRadius: 'var(--radius-pill)', padding: '12px 20px',
          fontFamily: 'var(--font-mono)', fontSize: 13, letterSpacing: '0.03em', color: 'var(--at-hermes)',
          transition: 'background var(--dur-fast)',
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = '#FFFFFF'}
        onMouseLeave={(e) => e.currentTarget.style.background = '#FBFAF8'}>{c}</button>
      ))}
    </div>
  );
}

function PageComposer({ onAsk }) {
  const [val, setVal] = React.useState('');
  const has = val.trim().length > 0;
  const submit = (e) => { e.preventDefault(); if (!has) return; if (onAsk) onAsk(val.trim()); setVal(''); };
  return (
    <form className="at-composer" onSubmit={submit} style={{
      display: 'flex', alignItems: 'center', gap: 12, background: '#FBFAF8',
      border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)',
      padding: '8px 8px 8px 20px', boxShadow: 'var(--shadow-md)',
    }}>
      <img src="/assets/athena-glyph.png" alt="" aria-hidden="true" style={{ width: 22, height: 'auto', opacity: 0.75, flex: 'none' }} />
      <input value={val} onChange={(e) => setVal(e.target.value)} placeholder="Ask Athena anything about title, closing, or getting started..." style={{
        flex: 1, border: 'none', outline: 'none', background: 'transparent',
        fontFamily: 'var(--font-mono)', fontSize: 16, letterSpacing: '0.02em', color: 'var(--text-primary)', padding: '16px 0',
      }} />
      <button type="submit" disabled={!has} style={{
        cursor: has ? 'pointer' : 'not-allowed', border: 'none',
        background: has ? 'var(--at-hermes)' : 'var(--at-cream-deep)',
        color: has ? '#fff' : 'var(--text-muted)', borderRadius: 'var(--radius-md)',
        padding: '16px 30px', fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 500,
        letterSpacing: '0.14em', textTransform: 'uppercase', transition: 'background var(--dur-fast), color var(--dur-fast)',
      }}>Send</button>
    </form>
  );
}

function AgenticPage({ title, subtitle, active, chips = [], children }) {
  const [act, setAct] = React.useState(active);
  const chat = useATChat();
  return (
    <div style={{ display: 'flex', height: '100%' }}>
      <window.Sidebar active={act} setActive={setAct} />
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, background: 'linear-gradient(180deg, #EFEEEA 0%, #E9E6E0 100%)' }}>
        <window.TopBar title={title} subtitle={subtitle} />
        <div style={{ flex: 1, position: 'relative', minHeight: 0 }}>
          {/* Athena is part of the surface itself, not a widget on top of it. */}
          <img className="at-watermark" src="/assets/athena-glyph.png" alt="" aria-hidden="true" style={{
            position: 'absolute', right: '-4%', top: '50%', transform: 'translateY(-50%)',
            width: 'min(46%, 520px)', opacity: 0.045, pointerEvents: 'none', userSelect: 'none',
          }} />
          <div className="at-thread" style={{ position: 'absolute', inset: 0, overflowY: 'auto', padding: '40px 0 240px' }}>
            <div style={{ maxWidth: 1080, margin: '0 auto', padding: '0 40px', display: 'flex', flexDirection: 'column', gap: 36 }}>
              {children}
              <ATMessages messages={chat.messages} pending={chat.pending} />
            </div>
          </div>
          <div className="at-bottom" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '0 40px 16px', background: 'linear-gradient(180deg, rgba(233,230,224,0) 0%, #E9E6E0 28%)' }}>
            <div style={{ maxWidth: 1080, margin: '0 auto' }}>
              <ATChipRow chips={chips} onAsk={chat.ask} />
              <PageComposer onAsk={chat.ask} />
              <div style={{ textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-muted)', marginTop: 14 }}>
                Agentic Title · AI-Assisted · Not Legal Advice · <a href="/privacy" onClick={(e) => { if (window.__goToPage) { e.preventDefault(); window.__goToPage('Privacy Policy'); } }} style={{ color: 'inherit', textDecoration: 'underline', textUnderlineOffset: 3 }}>Privacy Policy</a>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { AgenticAvatar, AthenaAvatar, AgenticMessage, AgenticIntro, PageComposer, AgenticPage, useATChat, ATMessages, ATChipRow, ATUserBubble, ATAnswerBubble });
