// ============================================================
// IMPRINT — case study support components (v2 narrative)
// Personas (interactive switcher) + doodles, competitor audit
// w/ logos, decision cards, flow / IA / exploration diagrams.
// Copy source of truth: imprint-brief.md — wording is verbatim.
// Depends on globals from bubbles.jsx and imprint-screens.jsx.
// ============================================================
const { useState: useStateP } = React;

// ---- competitor logo (favicon with letter fallback) ----
function CompLogo({ domain, name, size = 20 }) {
  const [failed, setFailed] = useStateP(false);
  if (failed) {
    return <span className="cs-clogo-fallback" style={{ width: size, height: size, fontSize: Math.round(size * 0.55) }}>{name.charAt(0).toUpperCase()}</span>;
  }
  return (
    <img
      className="cs-clogo"
      style={{ width: size, height: size }}
      src={'https://www.google.com/s2/favicons?domain=' + domain + '&sz=64'}
      alt={name + ' logo'}
      onError={() => setFailed(true)}
    />
  );
}

// ---- competitor audit cards (copy verbatim from brief) ----
function CompetitorAudit() {
  const audits = [
    {
      cos: [{ d: 'n8n.io', n: 'n8n' }, { d: 'stack-ai.com', n: 'StackAI' }],
      verdict: 'Deep, but engineer-first',
      text: <React.Fragment>n8n and StackAI are genuinely powerful but built entirely for people comfortable with technical concepts. <strong>The interface assumes you know what a webhook is</strong> and why you would want one.</React.Fragment>,
    },
    {
      cos: [{ d: 'zapier.com', n: 'Zapier Agents' }],
      verdict: 'Same logic, friendlier wrapper',
      text: <React.Fragment>Zapier Agents has simplified the surface reasonably well but the mental model underneath is still conditional logic. <strong>If-this-then-that flows with a friendlier wrapper</strong> over the top.</React.Fragment>,
    },
    {
      cos: [{ d: 'lindy.ai', n: 'Lindy AI' }, { d: 'intercom.com', n: 'Intercom Fin' }],
      verdict: 'Usable, but shallow',
      text: <React.Fragment>Lindy AI and Intercom Fin come the closest to something a non-technical user could get through but they achieve that by <strong>keeping configuration very shallow</strong>. You can set a tone and a few basic rules but you cannot really teach the agent how to handle anything nuanced.</React.Fragment>,
    },
  ];
  return (
    <div className="cs-audit">
      {audits.map((a, i) => (
        <div key={i} className="cs-audit-card reveal">
          <div className="cs-audit-logos">
            {a.cos.map((c, j) => (
              <span key={j} className="cs-audit-co"><CompLogo domain={c.d} name={c.n} /> {c.n}</span>
            ))}
          </div>
          <div className="cs-audit-verdict">{a.verdict}</div>
          <p>{a.text}</p>
        </div>
      ))}
    </div>
  );
}

// ---- persona doodles ----
function MayaDoodle() {
  return (
    <svg className="cs-doodle" viewBox="0 0 120 120" aria-hidden="true">
      <circle cx="60" cy="60" r="56" fill="#F1ECFA"></circle>
      <path d="M26 110 C32 90 45 83 60 83 C75 83 88 90 94 110" fill="#FFFFFF" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <circle cx="60" cy="56" r="25" fill="#FFFFFF" stroke="#2A2433" strokeWidth="3"></circle>
      <path d="M36 62 C30 34 45 25 60 25 C75 25 90 34 84 62 C83 48 75 41 60 41 C45 41 37 48 36 62 Z" fill="#8B6FD4" stroke="#2A2433" strokeWidth="3" strokeLinejoin="round"></path>
      <path d="M33 50 C33 31 45 20 60 20 C75 20 87 31 87 50" fill="none" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <rect x="28" y="47" width="10" height="17" rx="5" fill="#2A2433"></rect>
      <rect x="82" y="47" width="10" height="17" rx="5" fill="#2A2433"></rect>
      <path d="M35 64 C37 74 45 79 53 80" fill="none" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <circle cx="55" cy="80" r="3.5" fill="#2A2433"></circle>
      <circle cx="52" cy="57" r="2.6" fill="#2A2433"></circle>
      <circle cx="69" cy="57" r="2.6" fill="#2A2433"></circle>
      <path d="M54 68 C58 72 64 72 68 68" fill="none" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <circle cx="46" cy="63" r="3" fill="#EFA6BF" opacity="0.75"></circle>
      <circle cx="75" cy="63" r="3" fill="#EFA6BF" opacity="0.75"></circle>
    </svg>
  );
}

function JordanDoodle() {
  return (
    <svg className="cs-doodle" viewBox="0 0 120 120" aria-hidden="true">
      <circle cx="60" cy="60" r="56" fill="#FAEDF2"></circle>
      <path d="M26 110 C32 90 45 83 60 83 C75 83 88 90 94 110" fill="#FFFFFF" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <path d="M52 85 L60 94 L68 85" fill="none" stroke="#2A2433" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"></path>
      <circle cx="60" cy="56" r="25" fill="#FFFFFF" stroke="#2A2433" strokeWidth="3"></circle>
      <path d="M36 54 C34 35 44 26 60 26 C76 26 86 35 84 54 C79 44 72 40 60 40 C48 40 41 44 36 54 Z" fill="#C26B8F" stroke="#2A2433" strokeWidth="3" strokeLinejoin="round"></path>
      <rect x="43" y="50" width="14" height="12" rx="5" fill="none" stroke="#2A2433" strokeWidth="3"></rect>
      <rect x="63" y="50" width="14" height="12" rx="5" fill="none" stroke="#2A2433" strokeWidth="3"></rect>
      <path d="M57 55 L63 55" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <circle cx="50" cy="56" r="2.4" fill="#2A2433"></circle>
      <circle cx="70" cy="56" r="2.4" fill="#2A2433"></circle>
      <path d="M54 70 C58 73 64 73 68 70" fill="none" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <circle cx="44" cy="64" r="3" fill="#EFA6BF" opacity="0.6"></circle>
      <circle cx="76" cy="64" r="3" fill="#EFA6BF" opacity="0.6"></circle>
    </svg>
  );
}

// new-to-AI user (third story) — simple anonymous doodle
function NewUserDoodle() {
  return (
    <svg className="cs-doodle" viewBox="0 0 120 120" aria-hidden="true">
      <circle cx="60" cy="60" r="56" fill="#EDEFF9"></circle>
      <path d="M26 110 C32 90 45 83 60 83 C75 83 88 90 94 110" fill="#FFFFFF" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <circle cx="60" cy="56" r="25" fill="#FFFFFF" stroke="#2A2433" strokeWidth="3"></circle>
      <path d="M37 52 C37 32 46 25 60 25 C74 25 83 32 83 52 C79 41 70 38 60 39 C49 40 41 44 37 52 Z" fill="#6D7CE0" stroke="#2A2433" strokeWidth="3" strokeLinejoin="round"></path>
      <circle cx="52" cy="56" r="2.6" fill="#2A2433"></circle>
      <circle cx="69" cy="56" r="2.6" fill="#2A2433"></circle>
      <path d="M54 68 C58 72 64 72 68 68" fill="none" stroke="#2A2433" strokeWidth="3" strokeLinecap="round"></path>
      <circle cx="46" cy="63" r="3" fill="#EFA6BF" opacity="0.6"></circle>
      <circle cx="75" cy="63" r="3" fill="#EFA6BF" opacity="0.6"></circle>
    </svg>
  );
}

// ---- persona data (verbatim from brief) ----
const IMP_PERSONAS = {
  maya: {
    name: 'Maya',
    short: 'CS team lead',
    role: 'Customer service team lead · mid-sized SaaS',
    quote: "I know exactly how I'd handle every situation. I just can't get that into the tool.",
    bio: 'Maya is a customer service team lead at a mid-sized SaaS company. She manages a team of eight, knows the support process inside out and has strong opinions about how difficult conversations should be handled. She was asked to set up the team\u2019s AI agent, spent forty minutes in the tool before giving up and handed it to someone in IT. The agent technically works but does not behave the way she would.',
    goals: [
      'Get an agent that reflects how her team actually works, not a generic approximation of it',
      'Configure and update it herself without depending on engineering support',
      'Feel confident the agent will not say something wrong to a customer',
    ],
    frus: [
      'Every tool she has tried expects her to think in logic and conditions rather than situations',
      'When she does get help setting it up, something always gets lost in translation',
      'No way to verify the agent is behaving correctly until something goes wrong',
    ],
  },
  jordan: {
    name: 'Jordan',
    short: 'Operations manager',
    role: 'Operations manager · e-commerce brand',
    quote: "I need to move fast and I can't be going back to the dev team every time something changes.",
    bio: 'Jordan is an operations manager at an e-commerce brand overseeing several customer-facing workflows across different channels. He is comfortable enough with technology to get further than Maya before hitting a wall, but not technical in the engineering sense. He needs to configure agents for multiple scenarios and update them regularly as processes evolve.',
    goals: [
      'Set up and adjust agents quickly without creating a bottleneck with the technical team',
      'Keep configurations up to date as business processes change',
      'Have visibility over what each agent is doing and why',
    ],
    frus: [
      'Current tools require too much technical knowledge to update without help',
      'Changes to workflows take too long to reflect in the agent',
      'No easy way to see what the agent actually knows versus what he thinks it knows',
    ],
  },
};

// ---- interactive persona switcher ----
function Personas() {
  const [who, setWho] = useStateP('maya');
  const d = IMP_PERSONAS[who];
  const doodle = who === 'maya' ? <MayaDoodle /> : <JordanDoodle />;
  return (
    <div className="reveal">
      <div className="cs-ptabs">
        {['maya', 'jordan'].map(k => (
          <button key={k} className={'cs-ptab' + (who === k ? ' on' : '')} onClick={() => setWho(k)}>
            {k === 'maya' ? <MayaDoodle /> : <JordanDoodle />}
            <span className="pt-txt">
              <span className="pt-name">{IMP_PERSONAS[k].name}</span>
              <span className="pt-role">{IMP_PERSONAS[k].short}</span>
            </span>
          </button>
        ))}
      </div>
      <div className="cs-persona" key={who}>
        <div className="cs-persona-top">
          {doodle}
          <div className="cs-persona-id">
            <div className="cs-persona-name">{d.name}</div>
            <div className="cs-persona-role">{d.role}</div>
            <p className="cs-persona-quote">"{d.quote}"</p>
          </div>
        </div>
        <p className="cs-persona-bio">{d.bio}</p>
        <div className="cs-persona-lists">
          <div className="cs-plist goals">
            <h5>Goals</h5>
            <ul>{d.goals.map((g, i) => <li key={i}>{g}</li>)}</ul>
          </div>
          <div className="cs-plist frus">
            <h5>Frustrations</h5>
            <ul>{d.frus.map((f, i) => <li key={i}>{f}</li>)}</ul>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- user stories (verbatim, with persona doodles) ----
function UserStories() {
  const stories = [
    { doodle: <MayaDoodle />, role: 'a customer service lead', want: 'to describe how my team handles situations in plain language', so: 'the agent behaves the way I actually would.' },
    { doodle: <JordanDoodle />, role: 'an operations manager', want: 'to update my agent\u2019s behaviour quickly as processes change', so: 'I am not dependent on technical support every time.' },
    { doodle: <NewUserDoodle />, role: 'a first-time user', want: 'to see how the agent will respond before it goes live', so: 'I can feel confident activating it.' },
  ];
  return (
    <div className="cs-stories">
      {stories.map((s, i) => (
        <div key={i} className="cs-story reveal">
          <div className="st-doodle">{s.doodle}</div>
          <span className="k">As</span>
          <span className="as">{s.role},</span>
          <span className="k">I want</span>
          {s.want},
          <span className="k">so that</span>
          <span className="so">{s.so}</span>
        </div>
      ))}
    </div>
  );
}

// ---- decision cards (before → after, plus standalone notes) ----
function DecPair({ from, to }) {
  return (
    <div className="cs-dec-pair reveal">
      <div className="cs-dec">
        <span className="cs-dec-tag fail">✕ Tried first</span>
        <h4>{from.t}</h4>
        <p>{from.d}</p>
      </div>
      <div className="cs-dec-arrow">→</div>
      <div className="cs-dec final">
        <span className="cs-dec-tag win">✓ Final call</span>
        <h4>{to.t}</h4>
        <p>{to.d}</p>
      </div>
    </div>
  );
}

function DecNote({ tag = '▸ Design decision', tone = 'note', title, span = false, children }) {
  return (
    <div className={'cs-dec reveal' + (span ? ' span' : '') + (tone === 'hero' ? ' hero' : '')}>
      <span className={'cs-dec-tag ' + tone}>{tag}</span>
      <h4>{title}</h4>
      <p>{children}</p>
    </div>
  );
}

// ---- current-state user flow with breakdown ----
function UserFlow() {
  const nodes = [
    { n: '01', t: 'Open agent builder' },
    { n: '02', t: 'Create a project' },
    { n: '03', t: 'Name the agent' },
    { n: '04', t: 'Configure logic & triggers', broken: true },
    { n: '05', t: 'Test behaviour' },
    { n: '06', t: 'Deploy' },
  ];
  return (
    <div className="reveal">
      <div className="cs-flow">
        {nodes.map((nd, i) => (
          <React.Fragment key={i}>
            <div className={'cs-flow-node' + (nd.broken ? ' broken' : '')}>
              {nd.broken && <span className="cs-flow-break">Breakdown</span>}
              <div className="fn-n">{nd.n}</div>
              <div className="fn-t">{nd.t}</div>
            </div>
            {i < nodes.length - 1 && <div className="cs-flow-arrow">→</div>}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ---- interaction exploration wires ----
function ExploreWire({ kind }) {
  if (kind === 'form') {
    return (
      <div className="cs-dir-wire">
        <div style={{ position: 'absolute', inset: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ height: 8, width: '40%', background: 'var(--imp-line)', borderRadius: 4 }}></div>
          <div style={{ height: 22, background: '#fff', border: '1px solid var(--imp-line)', borderRadius: 5 }}></div>
          <div style={{ height: 8, width: '30%', background: 'var(--imp-line)', borderRadius: 4 }}></div>
          <div style={{ height: 22, background: '#fff', border: '1px solid var(--imp-line)', borderRadius: 5 }}></div>
        </div>
      </div>
    );
  }
  if (kind === 'drag') {
    return (
      <div className="cs-dir-wire">
        <div style={{ position: 'absolute', inset: 16, display: 'flex', gap: 8 }}>
          <div style={{ flex: 1, background: '#fff', border: '1px solid var(--imp-line)', borderRadius: 6 }}></div>
          <div style={{ flex: 1, background: 'var(--imp-tint)', border: '1px dashed var(--imp-primary)', borderRadius: 6 }}></div>
          <div style={{ flex: 1, background: '#fff', border: '1px solid var(--imp-line)', borderRadius: 6 }}></div>
        </div>
      </div>
    );
  }
  return (
    <div className="cs-dir-wire" style={{ background: 'var(--imp-tint)' }}>
      <div style={{ position: 'absolute', inset: 16, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 10 }}>
        <div style={{ alignSelf: 'flex-start', background: '#fff', border: '1px solid var(--imp-line)', borderRadius: '12px 12px 12px 4px', padding: '8px 12px', fontSize: 11, color: 'var(--imp-ink-2)', fontFamily: 'Inter, sans-serif', maxWidth: '78%' }}>What do you do when a customer wants to cancel?</div>
        <div style={{ alignSelf: 'flex-end', background: 'var(--imp-primary)', borderRadius: '12px 12px 4px 12px', padding: '8px 12px', fontSize: 11, color: '#fff', fontFamily: 'Inter, sans-serif', maxWidth: '78%' }}>I always ask what's prompting it first…</div>
      </div>
    </div>
  );
}

// rejected form direction, rendered in the product frame for the toggle
function FormDirection() {
  return (
    <div className="imp-screen">
      <div className="imp-top"><ImLogo /><Segs active={3} label="Step 3 of 5" /></div>
      <div className="imp-body">
        <h1 className="imp-h1">Configure agent behaviour</h1>
        <p className="imp-sub">Set the parameters for how your agent responds.</p>
        <div className="imp-card" style={{ marginTop: 26 }}>
          <div className="imp-field">
            <label className="imp-label">Tone of voice</label>
            <div className="imp-select"><span>Select tone…</span><span className="chev">▾</span></div>
          </div>
          <div className="imp-field">
            <label className="imp-label">Trigger keywords (comma separated)</label>
            <div className="imp-input"><span style={{ color: 'var(--imp-faint)' }}>cancel, refund, downgrade…</span></div>
          </div>
          <div className="imp-field" style={{ marginBottom: 0 }}>
            <label className="imp-label">Response phrases</label>
            <div className="imp-input"><span style={{ color: 'var(--imp-faint)' }}>Add canned phrase…</span></div>
          </div>
        </div>
        <p className="imp-foot-note" style={{ color: 'var(--imp-red)' }}>✕ A friendlier form is still a form.</p>
      </div>
    </div>
  );
}

function ExplorationToggle() {
  const [mode, setMode] = useStateP('conversation');
  return (
    <div className="cs-toggle-wrap reveal">
      <div className="cs-toggle-head">
        <div className="cs-toggle">
          <button className={mode === 'form' ? 'on' : ''} onClick={() => setMode('form')}>Direction 1 — Form</button>
          <button className={mode === 'conversation' ? 'on' : ''} onClick={() => setMode('conversation')}>Direction 3 — Conversation</button>
        </div>
        <span className="cs-toggle-note">Same task. Completely different mental model.</span>
      </div>
      {mode === 'form' ? (
        <Mockup url="app.imprint.ai/setup/playbook"><FormDirection /></Mockup>
      ) : (
        <Mockup url="app.imprint.ai/setup/playbook"><S3 onNext={() => {}} /></Mockup>
      )}
    </div>
  );
}

// ---- four-phase IA: horizontal rows, reads left to right ----
function IADiagram() {
  const phases = [
    { c: '#6D7CE0', n: '01', t: 'Setup', job: 'Get Maya oriented and comfortable before anything starts', screens: ['Welcome', 'Context'] },
    { c: '#8B6FD4', n: '02', t: 'Teach', job: 'The actual interview where the agent learns from her', screens: ['Playbook interview', 'Imprint confirms', 'Guardrails'] },
    { c: '#B47AAC', n: '03', t: 'Trust', job: 'A chance to see the agent in action and fix anything before going live', screens: ['Agent preview', 'Correction mode'] },
    { c: '#C26B8F', n: '04', t: 'Live', job: 'The handoff, with Maya staying in control', screens: ['Go live', 'Home dashboard'] },
  ];
  return (
    <div className="cs-ia-rows reveal">
      {phases.map((p, i) => (
        <div key={i} className="cs-ia-row">
          <div className="ph-id">
            <span className="n" style={{ background: p.c }}>{p.n}</span>
            <span className="t">{p.t}</span>
          </div>
          <div className="ph-job">{p.job}</div>
          <div className="ph-screens">
            {p.screens.map((s, j) => <span key={j} className="ph-screen">{s}</span>)}
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  CompLogo, CompetitorAudit,
  MayaDoodle, JordanDoodle, NewUserDoodle, Personas, UserStories,
  DecPair, DecNote, UserFlow, ExploreWire, FormDirection, ExplorationToggle, IADiagram,
});
