// ============================================================
// IMPRINT — product screens (own visual identity: Inter / slate blue)
// Reuses globals useState/useEffect/useRef declared in bubbles.jsx.
// ============================================================

// ---- logo mark ----
function ImLogo({ word = true }) {
  return (
    <div className="imp-logo">
      <div className="imp-logo-mark"><span className="sq1"></span><span className="sq2"></span></div>
      {word && <span className="imp-logo-word">imprint</span>}
    </div>
  );
}

function Segs({ active, total = 5, label }) {
  return (
    <div className="imp-segs">
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} className={'imp-seg' + (i + 1 < active ? ' done' : i + 1 === active ? ' active' : '')}></div>
      ))}
      {label && <span className="imp-seg-label">{label}</span>}
    </div>
  );
}

// ============ SCREEN 1 — Welcome ============
function S1({ onNext }) {
  return (
    <div className="imp-screen">
      <div className="imp-top"><ImLogo /><Segs active={1} label="Step 1 of 5" /></div>
      <div className="imp-body center">
        <h1 className="imp-h1" style={{ maxWidth: '18ch' }}>Set up your AI agent without writing a single line of code.</h1>
        <p className="imp-sub" style={{ margin: '16px auto 0' }}>Tell us how your team handles customer situations in your own words. Imprint builds your agent from your answers and lets you review it before anything goes live.</p>
        <div className="imp-stats">
          <div className="imp-stat"><div className="imp-stat-n">10 min</div><div className="imp-stat-l">To complete</div></div>
          <div className="imp-stat"><div className="imp-stat-n">5 steps</div><div className="imp-stat-l">Guided setup</div></div>
          <div className="imp-stat"><div className="imp-stat-n">You decide</div><div className="imp-stat-l">When it goes live</div></div>
        </div>
        <div style={{ width: '100%', maxWidth: 420 }}>
          <button className="imp-btn full" onClick={onNext}>Start setup</button>
          <div className="imp-foot-note" style={{ justifyContent: 'center' }}><span>🔒</span> Your agent will not go live until you review and approve it.</div>
        </div>
      </div>
    </div>
  );
}

// ============ SCREEN 2 — Context ============
function S2({ onNext }) {
  const [chan, setChan] = useState(['email', 'live chat']);
  const toggle = (c) => setChan((p) => p.includes(c) ? p.filter(x => x !== c) : [...p, c]);
  const channels = ['Email', 'Live chat', 'In-app', 'Slack'];
  return (
    <div className="imp-screen">
      <div className="imp-top"><ImLogo /><Segs active={2} label="Step 2 of 5" /></div>
      <div className="imp-body">
        <h1 className="imp-h1">Tell us about your team.</h1>
        <p className="imp-sub">A few quick details so your agent fits how you already work.</p>
        <div className="imp-card" style={{ marginTop: 28 }}>
          <div className="imp-field">
            <label className="imp-label">What will your agent handle?</label>
            <div className="imp-select"><span>Customer queries</span><span className="chev">▾</span></div>
          </div>
          <div className="imp-field">
            <label className="imp-label">Which channels?</label>
            <div className="imp-chipset">
              {channels.map(c => (
                <button key={c} className={'imp-chip' + (chan.includes(c.toLowerCase()) ? ' on' : '')} onClick={() => toggle(c.toLowerCase())}>
                  {chan.includes(c.toLowerCase()) && <span className="tick">✓</span>}{c}
                </button>
              ))}
            </div>
          </div>
          <div className="imp-field" style={{ marginBottom: 0 }}>
            <label className="imp-label">Conversations per week?</label>
            <div className="imp-input" style={{ maxWidth: 200 }}><span>250</span><span className="chev" style={{ display: 'flex', flexDirection: 'column', fontSize: 9, lineHeight: 1 }}>▲<br />▼</span></div>
          </div>
        </div>
        <div style={{ marginTop: 'auto', paddingTop: 24 }}><button className="imp-btn" onClick={onNext}>Continue</button></div>
      </div>
    </div>
  );
}

// ============ SCREEN 3 — Playbook interview ============
function S3({ onNext }) {
  const prev = [
    { t: 'Greeting a new customer', done: true },
    { t: 'Answering a billing question', done: true },
    { t: 'Handling a refund request', done: true },
  ];
  return (
    <div className="imp-screen">
      <div className="imp-top"><ImLogo /><Segs active={3} label="Step 3 of 5" /></div>
      <div className="imp-body">
        <div className="imp-split">
          <div className="imp-side">
            <div className="imp-side-h">Your answers</div>
            {prev.map((p, i) => (
              <div key={i} className="imp-side-item"><span className="dot">✓</span>{p.t}</div>
            ))}
            <div className="imp-side-item cur"><span className="dot">4</span>Cancellations</div>
          </div>
          <div className="imp-qwrap">
            <div className="imp-qnum">Question 4 of 6</div>
            <h2 className="imp-question">What do you do when a customer says they are thinking about cancelling?</h2>
            <textarea className="imp-textarea" rows={4} defaultValue="" placeholder="Answer in your own words — there's no right format." style={{ minHeight: 120 }}></textarea>
            <div className="imp-charcount">0 / 600</div>
            <div className="imp-qactions">
              <button className="imp-btn" onClick={onNext}>Submit answer</button>
              <button className="imp-link" onClick={onNext}>Skip this question</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ SCREEN 4 — Imprint confirms ============
function S4({ onNext }) {
  const [editing, setEditing] = useState(false);
  return (
    <div className="imp-screen">
      <div className="imp-top"><ImLogo /><Segs active={3} label="Step 3 of 5" /></div>
      <div className="imp-body" style={{ justifyContent: 'center' }}>
        <div style={{ maxWidth: 620, margin: '0 auto', width: '100%' }}>
          <p className="imp-mini-label" style={{ color: 'var(--imp-primary)' }}>Here is how your agent will understand that</p>
          <div className="imp-answer-card">
            <div className="imp-mini-label">Your answer</div>
            <div className="imp-answer-text">"I always try to understand why first. I ask what's prompting it, then see if there's a plan that fits better or a discount I can offer. I never let them go without flagging it to me."</div>
          </div>
          <div className="imp-interp">
            <div className="imp-interp-head"><ImLogo /></div>
            {!editing ? (
              <ul>
                <li>Lead with empathy — ask what is prompting the cancellation before offering anything.</li>
                <li>Suggest a better-fit plan or an available discount.</li>
                <li>Always flag a potential cancellation to a human.</li>
              </ul>
            ) : (
              <textarea className="imp-textarea" style={{ minHeight: 110, fontSize: 14 }} defaultValue={"Lead with empathy — ask what is prompting the cancellation before offering anything. Suggest a better-fit plan or an available discount. Always flag a potential cancellation to a human."}></textarea>
            )}
            <div className="imp-interp-actions">
              <button className="imp-btn" onClick={onNext}>That is right</button>
              <button className="imp-btn ghost" onClick={() => setEditing(e => !e)}>{editing ? 'Done editing' : 'Edit this'}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ SCREEN 5 — Guardrails ============
function S5({ onNext }) {
  const [adding, setAdding] = useState(false);
  const rules = [
    { tag: 'Billing', t: 'Any request for a refund over $500.' },
    { tag: 'Legal', t: 'A customer mentions legal action, disputes, or chargebacks.' },
    { tag: 'Escalation', t: 'The customer asks to speak to a manager directly.' },
  ];
  return (
    <div className="imp-screen">
      <div className="imp-top"><ImLogo /><Segs active={4} label="Step 4 of 5" /></div>
      <div className="imp-body">
        <h1 className="imp-h1">When should your agent always hand off to a human?</h1>
        <p className="imp-sub">Teach your agent when to ask for help.</p>
        <div className="imp-rules">
          {rules.map((r, i) => (
            <div key={i} className="imp-rule"><span className="imp-rule-tag">{r.tag}</span><span className="imp-rule-text">{r.t}</span></div>
          ))}
          {adding ? (
            <div className="imp-rule" style={{ borderColor: 'var(--imp-primary)', boxShadow: '0 0 0 3px rgba(59,91,219,.1)' }}>
              <span className="imp-rule-tag">New</span>
              <input className="imp-textarea" style={{ minHeight: 0, height: 38, padding: '8px 12px', fontSize: 14 }} placeholder="Describe the situation in your own words…" autoFocus />
            </div>
          ) : null}
          <button className="imp-rule-add" onClick={() => setAdding(a => !a)}><span style={{ fontSize: 18 }}>＋</span>{adding ? 'Save rule' : 'Add a rule'}</button>
        </div>
        <div style={{ marginTop: 'auto', paddingTop: 8 }}><button className="imp-btn" onClick={onNext}>Continue</button></div>
      </div>
    </div>
  );
}

// ============ Shared chat (Screens 6 & 7) ============
const IMP_CHAT = [
  { who: 'cust', t: "Hi, I've been having trouble getting the export feature to work all week." },
  { who: 'agent', t: "I'm sorry that's been frustrating. Exports can fail when a report is very large — can I check which one you're exporting?", ok: true },
  { who: 'cust', t: "Honestly I'm close to just cancelling. This keeps happening." },
  { who: 'agent', t: "I understand. I can cancel your plan right away if that's what you'd prefer.", flagged: true },
];

function ChatScreen({ stage = 'preview', onNext }) {
  // stage: 'preview' (flagged visible) | 'correction' (panel open) | 'corrected'
  const [tab, setTab] = useState(2); // churn risk
  const tabs = ['New customer', 'Frustrated customer', 'Churn risk'];
  return (
    <div className="imp-screen">
      <div className="imp-top"><ImLogo /><Segs active={5} label="Step 5 of 5" /></div>
      <div className="imp-body" style={{ paddingBottom: 28 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h1 className="imp-h1">Meet your agent.</h1>
        </div>
        <div className="imp-tabs" style={{ marginTop: 16 }}>
          {tabs.map((t, i) => <div key={i} className={'imp-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{t}</div>)}
        </div>
        <div className="imp-chat">
          {IMP_CHAT.map((m, i) => {
            const isFlag = m.flagged && (stage === 'preview' || stage === 'correction');
            const isCorrected = m.flagged && stage === 'corrected';
            return (
              <div key={i} className={'imp-msg ' + m.who + (isFlag ? ' flagged' : '')}>
                {m.who === 'agent' && <span className="imp-msg-icon">{isFlag ? '⚑' : '✓'}</span>}
                <div>
                  <div className="imp-bubble">{isCorrected ? "I hear you, and I don't want to lose you over this. Let me get the export issue fixed first — I'm flagging this to a specialist now so we can make it right." : m.t}</div>
                  {isCorrected && <div className="imp-corrected-chip">✓ Corrected</div>}
                </div>
              </div>
            );
          })}
          {stage === 'correction' && (
            <div className="imp-correct">
              <div className="imp-correct-h"><span style={{ color: 'var(--imp-red)' }}>⚑</span> What should it have said instead?</div>
              <textarea className="imp-textarea" defaultValue="I hear you, and I don't want to lose you over this. Let me get the export issue fixed first — I'm flagging this to a specialist now so we can make it right."></textarea>
              <div className="imp-correct-actions">
                <button className="imp-btn" onClick={onNext}>Save correction</button>
              </div>
            </div>
          )}
        </div>
        {stage === 'preview' && <div style={{ marginTop: 16 }}><button className="imp-btn" onClick={onNext}>Review flagged response</button></div>}
        {stage === 'corrected' && <div style={{ marginTop: 16 }}><button className="imp-btn" onClick={onNext}>Looks good — continue</button></div>}
      </div>
    </div>
  );
}

// ============ SCREEN 8 — Go live ============
function S8({ onNext }) {
  return (
    <div className="imp-screen">
      <div className="imp-top"><ImLogo /><Segs active={5} total={5} /></div>
      <div className="imp-body center">
        <h1 className="imp-h1">Your agent is ready.</h1>
        <p className="imp-sub" style={{ margin: '14px auto 0' }}>Here's everything you set up. Nothing goes live until you press the button.</p>
        <div className="imp-summary">
          <div className="imp-summary-row"><span className="k"><span className="ico">◎</span> Channels active</span><span className="v">Email · Live chat</span></div>
          <div className="imp-summary-row"><span className="k"><span className="ico">⚑</span> Escalation rules</span><span className="v">3 rules</span></div>
          <div className="imp-summary-row"><span className="k"><span className="ico">✦</span> Playbook topics covered</span><span className="v">6 topics</span></div>
        </div>
        <div className="imp-golive-actions">
          <button className="imp-btn full" onClick={onNext}>Activate agent</button>
          <button className="imp-link" onClick={onNext}>Not ready, keep editing</button>
        </div>
      </div>
    </div>
  );
}

// ============ SCREEN 9 — Home dashboard ============
function S9() {
  const convs = [
    { n: 'Maya R.', t: 'Billing question', o: 'Resolved', c: 'resolved' },
    { n: 'Tom B.', t: 'Export not working', o: 'Flagged', c: 'flagged' },
    { n: 'Priya N.', t: 'Considering cancelling', o: 'Handed off', c: 'handoff' },
    { n: 'Leo K.', t: 'Onboarding help', o: 'Resolved', c: 'resolved' },
  ];
  return (
    <div className="imp-dash">
      <div className="imp-dash-nav">
        <ImLogo />
        <div className="right">
          <span className="imp-pill-active"><span className="d"></span> Active</span>
          <button className="imp-pause">⏸ Pause agent</button>
        </div>
      </div>
      <div className="imp-dash-banner">
        <span className="flagico">⚑</span>
        Your agent flagged 2 conversations for review.
        <button className="imp-link">Review now</button>
      </div>
      <div className="imp-dash-grid">
        <div className="imp-dash-card">
          <h4>Today</h4>
          <div className="imp-today-n">38</div>
          <div className="imp-today-l">conversations handled</div>
          <svg className="imp-spark" width="100%" height="60" viewBox="0 0 240 60" preserveAspectRatio="none">
            <polyline points="0,46 30,40 60,44 90,28 120,32 150,18 180,24 210,10 240,16" fill="none" stroke="#3B5BDB" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
            <polyline points="0,46 30,40 60,44 90,28 120,32 150,18 180,24 210,10 240,16 240,60 0,60" fill="rgba(59,91,219,0.08)" stroke="none" />
          </svg>
        </div>
        <div className="imp-dash-card">
          <h4>Recent conversations</h4>
          <div style={{ marginTop: 6 }}>
            {convs.map((c, i) => (
              <div key={i} className="imp-conv">
                <span className="av">{c.n[0]}</span>
                <div><div className="nm">{c.n}</div><div className="tp">{c.t}</div></div>
                <span className={'out ' + c.c}>{c.o}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ Browser-frame mockup with scale-to-fit ============
// canvasWidth/canvasHeight describe the screen's real intrinsic size —
// defaults match Imprint's fixed 960x640 artboards. Pass the real size
// for screens built at a different canvas (e.g. Rio Tinto's 1440x900)
// so nothing gets cropped before it's scaled to fit its container.
function Mockup({ url = 'app.imprint.ai/setup', children, maxScale = 1, canvasWidth = 960, canvasHeight = 640 }) {
  const ref = useRef(null);
  const [scale, setScale] = useState(0.46);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const measure = () => { const w = el.clientWidth; if (w) setScale(Math.min(maxScale, w / canvasWidth)); };
    measure();
    const ro = new ResizeObserver(measure); ro.observe(el);
    return () => ro.disconnect();
  }, [maxScale, canvasWidth]);
  return (
    <div className="imp-mock">
      <div className="imp-mock-bar">
        <div className="imp-mock-lights"><span className="l1"></span><span className="l2"></span><span className="l3"></span></div>
        <div className="imp-mock-url"><span className="lock"></span>{url}</div>
      </div>
      <div className="imp-mock-view" ref={ref} style={{ height: Math.round(canvasHeight * scale) }}>
        <div className="imp-mock-screen" style={{ width: canvasWidth, height: canvasHeight, transform: 'scale(' + scale + ')' }}>{children}</div>
      </div>
    </div>
  );
}

// ============ Full clickable prototype (hero) ============
const IMP_SEQUENCE = [
  { key: 'welcome', url: 'app.imprint.ai/setup', render: (next) => <S1 onNext={next} /> },
  { key: 'context', url: 'app.imprint.ai/setup/context', render: (next) => <S2 onNext={next} /> },
  { key: 'interview', url: 'app.imprint.ai/setup/playbook', render: (next) => <S3 onNext={next} /> },
  { key: 'confirm', url: 'app.imprint.ai/setup/playbook', render: (next) => <S4 onNext={next} /> },
  { key: 'guardrails', url: 'app.imprint.ai/setup/guardrails', render: (next) => <S5 onNext={next} /> },
  { key: 'preview', url: 'app.imprint.ai/setup/preview', render: (next) => <ChatScreen stage="preview" onNext={next} /> },
  { key: 'correction', url: 'app.imprint.ai/setup/preview', render: (next) => <ChatScreen stage="correction" onNext={next} /> },
  { key: 'golive', url: 'app.imprint.ai/setup/go-live', render: (next) => <S8 onNext={next} /> },
  { key: 'dashboard', url: 'app.imprint.ai/home', render: () => <S9 /> },
];
const IMP_STEP_NAMES = ['Welcome', 'Context', 'Interview', 'Confirm', 'Guardrails', 'Preview', 'Correction', 'Go live', 'Dashboard'];

function ImprintPrototype({ maxScale = 1 }) {
  const [i, setI] = useState(0);
  const next = () => setI(p => Math.min(IMP_SEQUENCE.length - 1, p + 1));
  const prev = () => setI(p => Math.max(0, p - 1));
  const step = IMP_SEQUENCE[i];
  return (
    <div className="imp-proto">
      <Mockup url={step.url} maxScale={maxScale}>{step.render(next)}</Mockup>
      <div className="imp-proto-controls">
        <button className="imp-proto-btn" onClick={prev} disabled={i === 0} aria-label="Previous screen">←</button>
        <div className="imp-proto-step"><b>{IMP_STEP_NAMES[i]}</b> · {i + 1} / {IMP_SEQUENCE.length}</div>
        <button className="imp-proto-btn" onClick={next} disabled={i === IMP_SEQUENCE.length - 1} aria-label="Next screen">→</button>
      </div>
      <div className="imp-proto-dots">
        {IMP_SEQUENCE.map((_, idx) => (
          <button key={idx} className={'imp-proto-dot' + (idx === i ? ' on' : '')} onClick={() => setI(idx)} aria-label={'Go to ' + IMP_STEP_NAMES[idx]}></button>
        ))}
      </div>
      <div className="imp-proto-hint">Click the buttons inside the screen, or use the arrows, to step through the full flow.</div>
    </div>
  );
}

// ============ Trust showcase (animated before/after for §11) ============
function TrustShowcase() {
  const [stage, setStage] = useState('preview');
  const cycle = { preview: 'correction', correction: 'corrected', corrected: 'preview' };
  const labels = { preview: 'Flagged response', correction: 'Correcting inline', corrected: 'Corrected' };
  return (
    <div>
      <div className="cs-toggle-head" style={{ marginBottom: 18 }}>
        <div className="cs-toggle">
          {['preview', 'correction', 'corrected'].map(s => (
            <button key={s} className={stage === s ? 'on' : ''} onClick={() => setStage(s)}>{labels[s]}</button>
          ))}
        </div>
        <span className="cs-toggle-note">Passive review becomes active teaching.</span>
      </div>
      <Mockup url="app.imprint.ai/setup/preview"><ChatScreen stage={stage} onNext={() => setStage(cycle[stage])} /></Mockup>
    </div>
  );
}

Object.assign(window, { ImLogo, Segs, S1, S2, S3, S4, S5, S8, S9, ChatScreen, Mockup, ImprintPrototype, TrustShowcase });
