/* Section C. 7 distinct handoff routes per spec.
   C.1 Triage-based · C.2 In-workflow consult · C.3 Document review (LegalZoom pathway)
   C.4 Limited-scope · C.5 Full representation · C.6 A2A referral · C.7 Crisis routing */

const HANDOFF_ROUTES = [
  {
    id: 'consult', code: 'C.2',
    title: 'In-workflow attorney consult',
    short: 'Pause and get an attorney\'s read',
    desc: 'Available from any workflow step. 15-minute initial chat is free; longer consults are priced.',
    options: [
      { label: '15-min initial chat', price: 'Free', time: 'Same-day', highlight: true },
      { label: '30-min consult', price: '$79', time: 'Within 24h' },
      { label: '60-min strategy session', price: '$149', time: 'Scheduled' },
    ],
    icon: Icons.user, tone: THEME.blue,
  },
  {
    id: 'review', code: 'C.3',
    title: 'Document review',
    short: 'Have an attorney review before you file',
    desc: 'The LegalZoom-settlement pathway. Reviewing attorney provides written feedback. You decide what to incorporate. Attorney does not file or appear.',
    options: [
      { label: '5-day standard review', price: '$99', time: '5 business days' },
      { label: '48-hour rush', price: '$179', time: '48 hours', highlight: true },
      { label: '24-hour priority', price: '$249', time: '24 hours' },
    ],
    icon: Icons.doc, tone: THEME.success, sla: true,
  },
  {
    id: 'limited', code: 'C.4',
    title: 'Limited-scope representation',
    short: 'Hire an attorney for part of the case',
    desc: 'Attorney handles a defined slice (e.g., just the hearing, just discovery). Engagement letter and scope defined in-platform.',
    options: [
      { label: 'Hearing representation only', price: 'From $450', time: 'By hearing date' },
      { label: 'Discovery only', price: 'From $750', time: 'Per scope' },
      { label: 'Settlement negotiation only', price: 'From $350', time: 'Per scope' },
    ],
    icon: Icons.scale, tone: THEME.accent,
  },
  {
    id: 'full', code: 'C.5',
    title: 'Full representation',
    short: 'Hand off the entire matter',
    desc: 'Attorney takes over. Files appearance, takes over communications. Your account converts to "represented" status.',
    options: [
      { label: 'Flat-fee small claims', price: 'From $899', time: 'To resolution' },
      { label: 'Hourly engagement', price: '$185–$450/hr', time: 'Retainer' },
      { label: 'Contingency (eligible matters)', price: '25–40%', time: 'On recovery' },
    ],
    icon: Icons.shield, tone: THEME.blue,
  },
  {
    id: 'referral', code: 'C.6',
    title: 'Attorney-to-attorney referral',
    short: 'When the right attorney isn\'t the one you have',
    desc: 'Reviewing attorney recognizes the matter is beyond their expertise or jurisdiction. Refers to another verified attorney. Referral fee handling per jurisdictional rules.',
    options: [
      { label: 'In-network referral', price: 'Per jurisdiction', time: '24h match' },
    ],
    icon: Icons.link, tone: THEME.textDim,
  },
  {
    id: 'crisis', code: 'C.7',
    title: 'Escalation & crisis routing',
    short: 'When speed matters most',
    desc: 'Triggered automatically by keyword and pattern detection: imminent deadlines, criminal exposure, domestic violence, ICE detention, custody emergencies. Workflow pauses; specialized resources surfaced.',
    options: [
      { label: 'Crisis-matter intake', price: 'Free', time: 'Same-day', highlight: true },
      { label: 'National DV Hotline', price: '1-800-799-7233', time: '24/7' },
      { label: 'Specialized attorney directory', price: 'Curated', time: 'Same-day' },
    ],
    icon: Icons.alert, tone: THEME.danger, urgent: true,
  },
];

const HandoffV2 = ({ jx, onBack, initialRoute }) => {
  const [active, setActive] = React.useState(initialRoute || HANDOFF_ROUTES[0].id);
  const [booked, setBooked] = React.useState(null);
  const [composing, setComposing] = React.useState(null);
  const route = HANDOFF_ROUTES.find(r => r.id === active);

  // Build the prefilled email content from the active matter + selected
  // option. Uses window.V3_MATTERS[active matter] when available so the
  // intake description, jurisdiction, and case type carry through. The email
  // is dual-purpose: helps the client land a real consult AND pitches The
  // Law Guide's partner program to the attorney.
  const buildEmail = (opt, rt) => {
    const matterId = (typeof window !== 'undefined' && window.__activeMatterId) || 'newcase';
    const m = (typeof window !== 'undefined' && window.V3_MATTERS && window.V3_MATTERS[matterId]) || null;
    const caseType = (m && m.type) || 'Legal matter';
    const jxLabel = (m && m.jurisdiction) === 'utah' ? 'Utah' : 'New York';
    const summary = (m && m.summary) || 'Case details on file in Hello Court.';
    const clientName = (m && m.client && m.client.name) || 'A Law Guide client';
    return {
      to: '[Attorney name]',
      subject: `[Hello Court] ${caseType} / ${jxLabel} / ${opt.label}`,
      body: [
        `Hi,`,
        ``,
        `A client found you through Hello Court. They've already worked through a structured intake on our platform, so the basics of their matter are captured below. You'll get the full picture in 5 minutes instead of 30.`,
        ``,
        `ABOUT THE MATTER`,
        `Type: ${caseType}`,
        `Jurisdiction: ${jxLabel}`,
        `Requesting: ${opt.label}: ${opt.price} (${opt.time})`,
        `Route: ${rt.title} (${rt.code})`,
        ``,
        `THEIR DESCRIPTION`,
        `"${summary}"`,
        ``,
        `WHY THE LAW GUIDE`,
        `We're a sandbox-authorized legal-tech platform that helps consumers go from "not sure what I have" to "ready to talk to a lawyer." Clients arrive organized: facts gathered, evidence indexed, statutes identified, and a clear ask. For attorneys, that means consults that start at minute 5 instead of minute 35, clearer scope, and a steady pipeline of qualified, motivated leads.`,
        ``,
        `PARTNER PROGRAM`,
        `If you'd like to learn about our attorney partner program (revenue sharing, scheduled referrals, sandbox-authorized scope, vetted-client pipeline), reply with "PARTNER" and we'll set up a 15-minute platform walkthrough.`,
        ``,
        `Thanks for taking a look,`,
        `${clientName}, via Hello Court`,
        `client@example.com  ·  Reply to this thread to confirm`,
      ].join('\n'),
    };
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Header — no bottom border; relies on whitespace + scale to separate */}
      <div style={{ padding: '24px 32px 16px' }}>
        <div onClick={onBack} style={{ fontSize: 12, color: THEME.textDim, marginBottom: 8, cursor: 'pointer' }}>← Back to my matter</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: THEME.textMute, letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 600 }}>
              Section C · The Handoff Layer
            </div>
            <div style={{ fontFamily: 'Fraunces', fontSize: 30, color: THEME.text, fontWeight: 500, letterSpacing: -0.6, lineHeight: 1.1, marginTop: 4 }}>
              Get attorney help. Seven ways
            </div>
            <div style={{ fontSize: 13, color: THEME.textDim, marginTop: 6, maxWidth: 640, lineHeight: 1.5 }}>
              The handoff layer is the connective tissue between you and a verified attorney. Pick the right kind of help -
              from a 15-minute free chat to full representation. <span style={{ color: THEME.text, fontWeight: 500 }}>You decide; we route.</span>
            </div>
          </div>
        </div>
      </div>

      <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
        {/* Route list — no right divider */}
        <div style={{
          width: 320, padding: 18,
          overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 6,
        }}>
          {HANDOFF_ROUTES.map(r => {
            const a = active === r.id;
            return (
              <div key={r.id} onClick={() => setActive(r.id)} style={{
                padding: '11px 13px', borderRadius: 10, cursor: 'pointer',
                position: 'relative',
                background: a ? `${r.tone}15` : 'transparent',
                display: 'flex', alignItems: 'flex-start', gap: 11,
                transition: 'background 0.18s ease',
              }}>
                {a && (
                  <span aria-hidden="true" style={{
                    position: 'absolute', top: 6, bottom: 6, left: 1,
                    width: 4, borderRadius: '6px 0 0 6px',
                    background: r.tone,
                  }}/>
                )}
                <div style={{
                  width: 32, height: 32, borderRadius: 9, flexShrink: 0,
                  background: r.tone + '20', border: `1px solid ${r.tone}40`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon d={r.icon} size={14} stroke={r.tone}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                    <div style={{ fontSize: 9.5, color: THEME.textMute, letterSpacing: 0.6, fontWeight: 700 }}>{r.code}</div>
                    {r.urgent && <div style={{ fontSize: 9, padding: '1px 5px', borderRadius: 3, background: r.tone, color: '#D7DEE2', fontWeight: 700, letterSpacing: 0.5 }}>CRISIS</div>}
                  </div>
                  <div style={{ fontSize: 13, color: THEME.text, fontWeight: 600, marginBottom: 3 }}>{r.title}</div>
                  <div style={{ fontSize: 11.5, color: THEME.textDim, lineHeight: 1.4 }}>{r.short}</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Detail */}
        <div style={{ flex: 1, padding: 28, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <div style={{
                width: 44, height: 44, borderRadius: 12,
                background: route.tone + '20', border: `1px solid ${route.tone}40`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon d={route.icon} size={20} stroke={route.tone}/>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: THEME.textMute, letterSpacing: 1.2, fontWeight: 600 }}>HANDOFF · {route.code}</div>
                <div style={{ fontFamily: 'Fraunces', fontSize: 22, color: THEME.text, fontWeight: 500, letterSpacing: -0.3 }}>
                  {route.title}
                </div>
              </div>
            </div>
            <div style={{ fontSize: 13.5, color: THEME.textDim, lineHeight: 1.6, marginTop: 12 }}>
              {route.desc}
            </div>
          </div>

          {/* Options — each is a real button. Clicking books the option
              (mock for demo: shows a brief confirmation toast then bounces
              the user back to their matter). */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {route.options.map((opt, i) => (
              <div
                key={i}
                onClick={() => { setComposing({ option: opt, route, email: buildEmail(opt, route) }); }}
                onMouseEnter={(e) => { e.currentTarget.style.background = opt.highlight ? (THEME.mode === 'dark' ? 'rgba(105,134,191,0.18)' : 'rgba(105,134,191,0.14)') : (THEME.mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.85)'); }}
                onMouseLeave={(e) => { e.currentTarget.style.background = opt.highlight ? (THEME.mode === 'dark' ? 'rgba(105,134,191,0.10)' : 'rgba(105,134,191,0.08)') : 'transparent'; }}
                style={{
                  padding: '14px 16px', borderRadius: 11, cursor: 'pointer',
                  background: opt.highlight
                    ? (THEME.mode === 'dark' ? 'rgba(105,134,191,0.10)' : 'rgba(105,134,191,0.08)')
                    : 'transparent',
                  display: 'flex', alignItems: 'center', gap: 14,
                  transition: 'background 0.18s ease',
                }}>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                    <div style={{ fontSize: 13.5, color: THEME.text, fontWeight: 600 }}>{opt.label}</div>
                    {opt.highlight && <div style={{ fontSize: 9.5, padding: '2px 6px', borderRadius: 3, background: THEME.blue, color: '#D7DEE2', fontWeight: 700, letterSpacing: 0.4 }}>RECOMMENDED</div>}
                  </div>
                  <div style={{ fontSize: 11.5, color: THEME.textDim }}>SLA: {opt.time}</div>
                </div>
                <div style={{ fontFamily: 'Fraunces', fontSize: 18, color: THEME.text, fontWeight: 500 }}>{opt.price}</div>
                <div style={{
                  padding: '7px 14px', borderRadius: 8,
                  background: opt.highlight ? THEME.blue : '#1A2230',
                  color: '#F2F4F8',
                  fontSize: 12, fontWeight: 600,
                }}>Book this</div>
              </div>
            ))}
          </div>

          {/* SLA / sandbox notes for review route */}
          {route.sla && (
            <div style={{
              padding: '12px 14px', borderRadius: 10,
              background: THEME.mode === 'dark' ? 'rgba(255,255,255,0.025)' : 'rgba(0,0,0,0.025)',
              border: `1px dashed ${THEME.line}`,
              fontSize: 11.5, color: THEME.textDim, lineHeight: 1.55,
            }}>
              <div style={{ color: THEME.text, fontWeight: 600, marginBottom: 4 }}>How document review works</div>
              The reviewing attorney receives your intake, evidence, and the document with your specific concerns.
              They return written feedback with suggested edits. <span style={{ color: THEME.text, fontWeight: 500 }}>You decide what to incorporate.</span>
              The attorney does not file on your behalf and does not enter appearance. This is a limited-scope engagement under most state bar rules.
            </div>
          )}

          <NonAttorneyDisclosure jx={jx}/>
        </div>
      </div>

      {/* Email composer — opens after Book this. Shows a prefilled,
          editable email that introduces the client AND markets The Law
          Guide / partner program to the attorney. Send → booking
          confirmation. */}
      {composing && (
        <div onClick={() => setComposing(null)} style={{
          position: 'absolute', inset: 0, zIndex: 80,
          background: 'rgba(8,12,18,0.65)',
          WebkitBackdropFilter: 'blur(14px)', backdropFilter: 'blur(14px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32,
          animation: 'intakeFadeIn 0.22s ease-out',
        }}>
          <style>{`@keyframes intakeFadeIn { from { opacity: 0; } to { opacity: 1; } }`}</style>
          <div onClick={(e) => e.stopPropagation()} style={{
            width: 'min(640px, 100%)', maxHeight: '92%',
            background: THEME.glass, border: `1px solid ${THEME.glassBorder}`,
            borderRadius: 18,
            display: 'flex', flexDirection: 'column',
          }}>
            <div style={{ padding: '20px 24px 12px' }}>
              <div style={{ fontSize: 10.5, color: THEME.textMute, letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 600, marginBottom: 4 }}>Step 1 of 2 · Email the attorney</div>
              <div style={{ fontFamily: 'Fraunces', fontSize: 21, color: THEME.text, fontWeight: 500, letterSpacing: -0.4, lineHeight: 1.25 }}>
                Here's the email we'll send. Edit anything you want.
              </div>
              <div style={{ fontSize: 12, color: THEME.textDim, marginTop: 6, lineHeight: 1.55 }}>
                It introduces your case AND tells the attorney about Hello Court. Two birds, one email.
              </div>
            </div>
            <div style={{ padding: '8px 24px 0', flex: 1, minHeight: 0, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div>
                <div style={{ fontSize: 10.5, color: THEME.textHeader, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600, marginBottom: 4 }}>To</div>
                <input
                  type="text" value={composing.email.to}
                  onChange={(e) => setComposing(c => ({ ...c, email: { ...c.email, to: e.target.value } }))}
                  style={{
                    width: '100%', boxSizing: 'border-box',
                    padding: '8px 12px', borderRadius: 8,
                    background: THEME.mode === 'dark' ? 'rgba(255,255,255,0.025)' : 'rgba(255,255,255,0.65)',
                    border: `1px solid ${THEME.line}`, color: THEME.text,
                    fontSize: 13, fontFamily: 'inherit', outline: 'none',
                  }}/>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: THEME.textHeader, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600, marginBottom: 4 }}>Subject</div>
                <input
                  type="text" value={composing.email.subject}
                  onChange={(e) => setComposing(c => ({ ...c, email: { ...c.email, subject: e.target.value } }))}
                  style={{
                    width: '100%', boxSizing: 'border-box',
                    padding: '8px 12px', borderRadius: 8,
                    background: THEME.mode === 'dark' ? 'rgba(255,255,255,0.025)' : 'rgba(255,255,255,0.65)',
                    border: `1px solid ${THEME.line}`, color: THEME.text,
                    fontSize: 13, fontFamily: 'inherit', outline: 'none',
                  }}/>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: THEME.textHeader, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600, marginBottom: 4 }}>Body</div>
                <textarea
                  value={composing.email.body}
                  onChange={(e) => setComposing(c => ({ ...c, email: { ...c.email, body: e.target.value } }))}
                  rows={14}
                  style={{
                    width: '100%', boxSizing: 'border-box',
                    padding: '12px 14px', borderRadius: 8,
                    background: THEME.mode === 'dark' ? 'rgba(255,255,255,0.025)' : 'rgba(255,255,255,0.65)',
                    border: `1px solid ${THEME.line}`, color: THEME.text,
                    fontSize: 12.5, lineHeight: 1.55,
                    fontFamily: 'inherit', resize: 'vertical', outline: 'none',
                  }}/>
              </div>
              <div style={{ padding: '11px 13px', borderRadius: 9, background: THEME.mode === 'dark' ? 'rgba(255,255,255,0.025)' : 'rgba(0,0,0,0.025)', border: `1px dashed ${THEME.line}`, fontSize: 11.5, color: THEME.textDim, lineHeight: 1.5 }}>
                <span style={{ color: THEME.text, fontWeight: 600 }}>Why this works for both sides.</span> The attorney gets a structured intro that respects their time (clients arrive case-organized), and a soft pitch for our partner program. You get a real consult booked. We grow the network. Everybody wins.
              </div>
            </div>
            <div style={{ padding: '14px 24px 20px', display: 'flex', alignItems: 'center', gap: 12 }}>
              <Btn kind="secondary" onClick={() => setComposing(null)}>Cancel</Btn>
              <div style={{ flex: 1 }}/>
              <Btn kind="primary" onClick={() => { const c = composing; setComposing(null); setBooked({ option: c.option, route: c.route, email: c.email }); }}>
                Send and book
              </Btn>
            </div>
          </div>
        </div>
      )}

      {/* Booking confirmation — mock for the demo. Real flow would go to a
          scheduler / Calendly-style booking. Closes back to home or stays on
          this screen so the user can pick a different option. */}
      {booked && (
        <div onClick={() => setBooked(null)} style={{
          position: 'absolute', inset: 0, zIndex: 80,
          background: 'rgba(8,12,18,0.65)',
          WebkitBackdropFilter: 'blur(14px)', backdropFilter: 'blur(14px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32,
        }}>
          <div onClick={(e) => e.stopPropagation()} style={{
            width: 'min(440px, 100%)',
            background: THEME.glass, border: `1px solid ${THEME.glassBorder}`,
            borderRadius: 18, padding: 28,
            display: 'flex', flexDirection: 'column', gap: 14,
          }}>
            <div style={{
              width: 44, height: 44, borderRadius: 22,
              background: THEME.success + '20', border: `1px solid ${THEME.success}50`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon d={Icons.check} size={20} stroke={THEME.success} sw={2.4}/>
            </div>
            <div>
              <div style={{ fontFamily: 'Fraunces', fontSize: 20, color: THEME.text, fontWeight: 500, letterSpacing: -0.3, lineHeight: 1.3 }}>
                You're booked.
              </div>
              <div style={{ fontSize: 12.5, color: THEME.textDim, lineHeight: 1.55, marginTop: 6 }}>
                {booked.option.label} · {booked.option.price} · {booked.option.time}
              </div>
            </div>
            <div style={{ fontSize: 12.5, color: THEME.textDim, lineHeight: 1.55 }}>
              We'll email you a confirmation with the attorney's details and any prep we need before the call. Your case stays right where you left it.
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
              <Btn kind="secondary" onClick={() => setBooked(null)}>Pick something else</Btn>
              <div style={{ flex: 1 }}/>
              <Btn kind="primary" onClick={() => { setBooked(null); onBack && onBack(); }}>Back to my case</Btn>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

window.HANDOFF_ROUTES = HANDOFF_ROUTES;
window.HandoffV2 = HandoffV2;
