/* v2 Triage / Intake. Replaces v1 conversational intake.
   3-question Welcome+Triage flow per spec A.1: state, category, deadline.
   Output: Self-Service / Hybrid / Attorney Required (soft routing, never gates). */

const TRIAGE_CATEGORIES = [
  { id: 'small-claims', label: 'Small claims', icon: Icons.scale, hint: 'Under $10,000 (NY) or $15,000 (UT)' },
  { id: 'landlord', label: 'Landlord / tenant', icon: Icons.folder, hint: 'Lease, security deposit, eviction' },
  { id: 'employment', label: 'Employment', icon: Icons.user, hint: 'Wages, wrongful termination' },
  { id: 'consumer', label: 'Consumer', icon: Icons.shield, hint: 'Refunds, fraud, debt collection' },
  { id: 'family', label: 'Family', icon: Icons.bell, hint: 'Divorce, custody, support' },
  { id: 'business', label: 'Small business', icon: Icons.doc, hint: 'Vendor disputes, contracts' },
  { id: 'traffic', label: 'Traffic / vehicle', icon: Icons.flag, hint: 'Tickets, accidents under $5K' },
  { id: 'other', label: 'Something else', icon: Icons.book, hint: 'We\'ll route you to a consult' },
];

const TriageIntake = ({ jx, onClose, onFinish }) => {
  const [step, setStep] = React.useState(0);
  const [state, setState] = React.useState(jx === 'utah' ? 'UT' : 'NY');
  const [category, setCategory] = React.useState(null);
  const [deadline, setDeadline] = React.useState(null);

  const j = JURISDICTIONS[state.toLowerCase() === 'ut' ? 'utah' : 'ny'];

  // Triage outcome. 3 paths per spec
  const outcome = (() => {
    if (deadline === 'urgent' || category === 'family' || category === 'other') return 'attorney';
    if (deadline === '14days' || category === 'employment' || category === 'consumer') return 'hybrid';
    return 'self';
  })();

  const OUTCOMES = {
    self: {
      label: 'Self-Service appropriate', tone: THEME.success,
      title: 'You can handle this yourself with our help.',
      body: 'Your matter looks like a fit for our guided workflow. We\'ll walk you through fact gathering, choosing a legal theory, organizing evidence, and drafting court-formatted documents. You can request an attorney consult or document review at any point.',
      cta: 'Start guided workflow',
    },
    hybrid: {
      label: 'Hybrid recommended', tone: THEME.warning,
      title: 'Self-service plus an attorney touchpoint or two.',
      body: 'You can use the guided workflow to organize your matter, but we recommend an attorney consult or document review before you file. We\'ll surface the prompts at the right moments. You decide whether to take them.',
      cta: 'Start workflow with attorney touchpoints',
    },
    attorney: {
      label: 'Attorney consult recommended', tone: THEME.danger,
      title: 'This may benefit from full attorney engagement.',
      body: 'Based on your inputs, we recommend talking to a verified attorney before proceeding. The platform won\'t stop you from continuing self-service. But the safer path is to start with a 15-minute consult, free.',
      cta: 'Find a verified attorney',
    },
  };

  const steps = [
    {
      title: 'What state is this happening in?',
      sub: 'Jurisdictional law varies. Without your state, we can\'t do substantive work.',
      content: (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {Object.values(JURISDICTIONS).map(jj => {
            const a = state === jj.code;
            return (
              <div key={jj.id} onClick={() => setState(jj.code)} style={{
                padding: '14px 16px', borderRadius: 12, cursor: 'pointer',
                background: a ? (THEME.mode === 'dark' ? 'rgba(105,134,191,0.10)' : 'rgba(105,134,191,0.08)') : THEME.surface,
                border: `1.5px solid ${a ? THEME.blue : THEME.line}`,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{
                  width: 18, height: 18, borderRadius: 9, border: `1.5px solid ${a ? THEME.blue : THEME.lineSoft}`,
                  background: a ? THEME.blue : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {a && <div style={{ width: 7, height: 7, borderRadius: 4, background: '#fff' }}/>}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, color: THEME.text, fontWeight: 600 }}>{jj.name}</div>
                  <div style={{ fontSize: 11.5, color: THEME.textDim, marginTop: 2 }}>
                    {jj.posture === 'sandbox'
                      ? '✓ Sandbox-authorized · expanded features available'
                      : 'Educational framework · Dacey-protected'}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      ),
    },
    {
      title: 'What kind of legal issue are you dealing with?',
      sub: 'Pick the closest fit. You can change this later.',
      content: (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
          {TRIAGE_CATEGORIES.map(c => {
            const a = category === c.id;
            return (
              <div key={c.id} onClick={() => setCategory(c.id)} style={{
                padding: '14px 14px', borderRadius: 11, cursor: 'pointer',
                background: a ? (THEME.mode === 'dark' ? 'rgba(105,134,191,0.10)' : 'rgba(105,134,191,0.08)') : THEME.surface,
                border: `1.5px solid ${a ? THEME.blue : THEME.line}`,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 4 }}>
                  <Icon d={c.icon} size={15} stroke={a ? THEME.blue : THEME.textDim}/>
                  <div style={{ fontSize: 13.5, color: THEME.text, fontWeight: 600 }}>{c.label}</div>
                </div>
                <div style={{ fontSize: 11.5, color: THEME.textDim, marginLeft: 24 }}>{c.hint}</div>
              </div>
            );
          })}
        </div>
      ),
    },
    {
      title: 'Is anything pressing on a deadline?',
      sub: 'Court dates, statute of limitations, response windows. If you\'re not sure, pick "I\'m not sure".',
      content: (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { id: 'urgent', label: 'Yes. Within 7 days', tone: THEME.danger, sub: 'We\'ll surface urgency banners and prioritize attorney consult.' },
            { id: '14days', label: 'Yes. Within 14 days', tone: THEME.warning, sub: 'We\'ll recommend at least a document review before filing.' },
            { id: 'soon', label: 'Yes. Within 30 days', tone: THEME.success, sub: 'You have time. Self-service workflow fits.' },
            { id: 'none', label: 'No deadline pressing', tone: THEME.textDim, sub: 'No urgency. Full self-paced workflow.' },
            { id: 'unsure', label: "I'm not sure", tone: THEME.textMute, sub: 'Treated as a flag. We\'ll suggest checking with an attorney.' },
          ].map(d => {
            const a = deadline === d.id;
            return (
              <div key={d.id} onClick={() => setDeadline(d.id)} style={{
                padding: '12px 14px', borderRadius: 11, cursor: 'pointer',
                background: a ? (THEME.mode === 'dark' ? 'rgba(105,134,191,0.10)' : 'rgba(105,134,191,0.08)') : THEME.surface,
                border: `1.5px solid ${a ? THEME.blue : THEME.line}`,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{ width: 8, height: 8, borderRadius: 4, background: d.tone, flexShrink: 0 }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13.5, color: THEME.text, fontWeight: 600 }}>{d.label}</div>
                  <div style={{ fontSize: 11.5, color: THEME.textDim, marginTop: 2 }}>{d.sub}</div>
                </div>
              </div>
            );
          })}
        </div>
      ),
    },
    {
      title: OUTCOMES[outcome].title,
      sub: null,
      isOutcome: true,
      content: (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{
            padding: '16px 18px', borderRadius: 14,
            background: `linear-gradient(135deg, ${OUTCOMES[outcome].tone}15, transparent)`,
            border: `1.5px solid ${OUTCOMES[outcome].tone}50`,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <div style={{
                fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4,
                background: OUTCOMES[outcome].tone, color: '#fff', letterSpacing: 0.6,
              }}>{OUTCOMES[outcome].label.toUpperCase()}</div>
            </div>
            <div style={{ fontSize: 13, color: THEME.textDim, lineHeight: 1.55 }}>
              {OUTCOMES[outcome].body}
            </div>
          </div>

          {/* Soft routing emphasis */}
          <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,
            display: 'flex', alignItems: 'flex-start', gap: 8,
          }}>
            <Icon d={Icons.shield} size={13} stroke={THEME.textMute}/>
            <span>
              <span style={{ color: THEME.text, fontWeight: 600 }}>This is a recommendation, not a gate.</span> You can choose any path -
              including continuing self-service even if we suggest an attorney. The decision is yours.
            </span>
          </div>

          <NonAttorneyDisclosure jx={state.toLowerCase() === 'ut' ? 'utah' : 'ny'} compact/>
        </div>
      ),
    },
  ];

  const cur = steps[step];
  const canAdvance = step === 0 ? state : step === 1 ? category : step === 2 ? deadline : true;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 90,
      background: THEME.mode === 'dark' ? 'rgba(8,12,18,0.78)' : 'rgba(20,28,38,0.32)',
      WebkitBackdropFilter: 'blur(20px) saturate(140%)', backdropFilter: 'blur(20px) saturate(140%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40,
    }}>
      <div style={{
        width: 'min(620px, 100%)', maxHeight: '92%', overflow: 'auto',
        background: THEME.glass, border: `1px solid ${THEME.glassBorder}`,
        borderRadius: 22, boxShadow: '0 30px 80px rgba(0,0,0,0.4)',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Header */}
        <div style={{ padding: '20px 24px 14px', borderBottom: `1px solid ${THEME.line}`, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10.5, color: THEME.textMute, letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 600, marginBottom: 4 }}>
              {cur.isOutcome ? 'Triage result' : `Welcome & triage · step ${step + 1} of 3`}
            </div>
            <div style={{ fontFamily: 'Fraunces', fontSize: 22, color: THEME.text, fontWeight: 500, letterSpacing: -0.4, lineHeight: 1.2 }}>
              {cur.title}
            </div>
            {cur.sub && <div style={{ fontSize: 12.5, color: THEME.textDim, marginTop: 6, lineHeight: 1.5 }}>{cur.sub}</div>}
          </div>
          <div onClick={onClose} style={{
            width: 28, height: 28, borderRadius: 8, cursor: 'pointer',
            background: THEME.mode === 'dark' ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: THEME.textDim, fontSize: 16, fontWeight: 300,
          }}>×</div>
        </div>

        {/* Progress bar */}
        {!cur.isOutcome && (
          <div style={{ padding: '0 24px', marginTop: 12 }}>
            <div style={{ display: 'flex', gap: 5 }}>
              {[0, 1, 2].map(i => (
                <div key={i} style={{
                  flex: 1, height: 3, borderRadius: 2,
                  background: i <= step ? THEME.blue : THEME.lineSoft,
                }}/>
              ))}
            </div>
          </div>
        )}

        {/* Content */}
        <div style={{ padding: '20px 24px', flex: 1 }}>
          {cur.content}
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 24px 20px', borderTop: `1px solid ${THEME.line}`, display: 'flex', alignItems: 'center', gap: 12 }}>
          {step > 0 && !cur.isOutcome && (
            <div onClick={() => setStep(step - 1)} style={{
              padding: '9px 14px', borderRadius: 8, cursor: 'pointer', fontSize: 13, color: THEME.textDim, fontWeight: 500,
            }}>← Back</div>
          )}
          <div style={{ flex: 1 }}/>
          {!cur.isOutcome ? (
            <div onClick={() => canAdvance && setStep(step + 1)} style={{
              padding: '10px 20px', borderRadius: 9, cursor: canAdvance ? 'pointer' : 'not-allowed',
              background: canAdvance ? THEME.blue : THEME.lineSoft,
              color: canAdvance ? '#fff' : THEME.textMute,
              fontSize: 13, fontWeight: 600,
              opacity: canAdvance ? 1 : 0.5,
            }}>
              {step === 2 ? 'See triage result' : 'Continue'} →
            </div>
          ) : (
            <>
              <div onClick={() => setStep(0)} style={{
                padding: '9px 14px', borderRadius: 8, cursor: 'pointer', fontSize: 12.5, color: THEME.textDim, fontWeight: 500,
                border: `1px solid ${THEME.line}`,
              }}>Start over</div>
              <div onClick={() => onFinish && onFinish({ state, category, deadline, outcome })} style={{
                padding: '10px 20px', borderRadius: 9, cursor: 'pointer',
                background: OUTCOMES[outcome].tone, color: '#fff', fontSize: 13, fontWeight: 600,
              }}>{OUTCOMES[outcome].cta} →</div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

window.TriageIntake = TriageIntake;
