// Three ticket-create variants: AI parse, Guided form, Chat with AI
// All converge to "Find pro" → matching radar

// ── Variant 1: AI parse (photo + voice + describe) ────────────
const TicketAI = ({ nav, svc, dir }) => {
  const d = D(dir);
  const [text, setText] = React.useState('');
  const [recording, setRecording] = React.useState(false);
  const [recTime, setRecTime] = React.useState(0);
  const [photos, setPhotos] = React.useState([]);
  const [parsed, setParsed] = React.useState(null);

  React.useEffect(() => {
    if (!recording) return;
    const id = setInterval(() => setRecTime(t => t + 1), 1000);
    return () => clearInterval(id);
  }, [recording]);

  const stop = () => {
    setRecording(false);
    setText(t => t || 'Kitchen sink is leaking from underneath the counter. Started yesterday, getting worse. Drip every few seconds.');
  };

  const submit = () => {
    setParsed({ category: svc?.name || 'Plumbing', urgency: 'Today', est: '₹450–₹720', confidence: 96 });
    setTimeout(() => nav.go('matching', { ticket: { svc, desc: text } }), 1800);
  };

  return (
    <div style={{ padding: '0 18px 120px', minHeight: '100%' }}>
      <Header nav={nav} title="Describe the problem" subtitle="AI assist · faster than typing"/>

      {/* Photo strip */}
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.text3, textTransform: 'uppercase', marginBottom: 8 }}>Photos</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {[0,1,2].map(i => (
            <div key={i} onClick={() => setPhotos(p => p.includes(i) ? p.filter(x => x !== i) : [...p, i])} style={{
              flex: 1, height: 78, borderRadius: 14, cursor: 'pointer',
              background: photos.includes(i) ? `linear-gradient(135deg, ${Z.brand}33, ${Z.pink}22)` : d.panel,
              border: `${photos.includes(i) ? '1.5px' : '0.5px'} dashed ${photos.includes(i) ? Z.brand : d.border}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative',
              transition: 'all .15s',
            }}>
              {photos.includes(i)
                ? <div style={{ fontSize: 22 }}>📷</div>
                : <I.plus size={20} color={Z.text3}/>}
              {photos.includes(i) && <div style={{ position: 'absolute', top: 4, right: 4, width: 16, height: 16, borderRadius: '50%', background: Z.success, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}><I.check size={10} stroke={3}/></div>}
            </div>
          ))}
        </div>
      </div>

      {/* Voice */}
      <div style={{
        padding: 16, borderRadius: 16, marginBottom: 14,
        background: recording ? 'rgba(239,68,68,0.10)' : d.panel,
        border: `0.5px solid ${recording ? 'rgba(239,68,68,0.4)' : d.border}`,
      }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: recording ? Z.danger : Z.text3, textTransform: 'uppercase', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
          {recording && <div style={{ width: 6, height: 6, borderRadius: '50%', background: Z.danger, animation: 'blink 1s infinite' }}/>}
          Voice note · {recording ? `${fmtTime(recTime)} recording…` : 'tap to record'}
        </div>
        {/* waveform */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 2, height: 32, marginBottom: 12 }}>
          {Array.from({length: 28}).map((_, i) => (
            <div key={i} style={{
              flex: 1, height: `${recording ? 30 + Math.sin(i*0.7 + recTime*2)*40 + 30 : 20 + (i%5)*8}%`,
              background: recording ? Z.danger : Z.text4, borderRadius: 2,
              opacity: recording ? 0.8 : 0.4,
              transition: 'height .15s', animation: recording ? `wave 1.2s ${i*0.03}s infinite` : 'none',
            }}/>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div onClick={() => recording ? stop() : setRecording(true)} style={{
            width: 52, height: 52, borderRadius: '50%', cursor: 'pointer',
            background: recording ? Z.danger : Z.gradient,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
            boxShadow: `0 0 24px ${recording ? Z.danger : Z.brand}88`,
          }}>
            {recording
              ? <div style={{ width: 14, height: 14, background: '#fff', borderRadius: 3 }}/>
              : <svg width="20" height="20" viewBox="0 0 24 24" fill="#fff"><path d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3zM19 11a7 7 0 0 1-14 0M12 18v3M9 21h6" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round"/></svg>
            }
          </div>
        </div>
      </div>

      {/* Text */}
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.text3, textTransform: 'uppercase', marginBottom: 8 }}>Or type</div>
        <textarea value={text} onChange={e => setText(e.target.value)} placeholder="What's wrong? When did it start?" rows={3} style={{
          width: '100%', padding: 12, borderRadius: 14, fontFamily: Z.font, fontSize: 13.5,
          background: d.panel, border: `0.5px solid ${d.border}`, color: Z.text, outline: 'none', resize: 'none',
        }}/>
      </div>

      {/* AI parsed preview */}
      {text && (
        <div style={{
          padding: 14, borderRadius: 16, marginBottom: 22,
          background: 'rgba(124,58,237,0.10)', border: `1px solid ${Z.borderStrong}`,
          animation: 'fadeUp .3s',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
            <I.spark size={12} color={Z.brandLite}/>
            <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.brandLite, textTransform: 'uppercase' }}>AI understands</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', rowGap: 8, columnGap: 14, fontSize: 12 }}>
            <span style={{ color: Z.text3 }}>Category</span><span style={{ color: Z.text, fontWeight: 600 }}>Plumbing · Leak repair</span>
            <span style={{ color: Z.text3 }}>Urgency</span><span style={{ color: Z.text, fontWeight: 600 }}>Today (escalating)</span>
            <span style={{ color: Z.text3 }}>Skill level</span><span style={{ color: Z.text, fontWeight: 600 }}>L2 plumber</span>
            <span style={{ color: Z.text3 }}>Est. range</span><span style={{ ...mono, color: Z.text, fontWeight: 600 }}>₹450 – ₹720</span>
          </div>
          <div style={{ marginTop: 10, fontSize: 10.5, color: Z.text3 }}>
            {parsed ? <><span style={{ color: Z.success }}>● {parsed.confidence}% confident</span> — confirming with a pro</> : '● 96% confident · you can edit before sending'}
          </div>
        </div>
      )}

      <button onClick={submit} disabled={!text || parsed} style={{
        ...btnPrimaryStyle, width: '100%', opacity: text ? 1 : 0.5,
      }}>
        {parsed ? <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
          <span style={{ width: 14, height: 14, border: `2px solid rgba(255,255,255,0.3)`, borderTopColor: '#fff', borderRadius: '50%', animation: 'spin .8s linear infinite' }}/>
          Finding pros…
        </span> : 'Find a pro →'}
      </button>
    </div>
  );
};

// ── Variant 2: Guided form ────────────────────────────────────
const TicketGuided = ({ nav, svc, dir }) => {
  const d = D(dir);
  const [step, setStep] = React.useState(0);
  const [issue, setIssue] = React.useState(null);
  const [when, setWhen] = React.useState('asap');
  const [notes, setNotes] = React.useState('');

  const issues = ['Leak under sink', 'Tap not working', 'Drain blocked', 'Low pressure', 'Burst pipe', 'Other'];

  const steps = ['Issue', 'When', 'Details', 'Review'];

  return (
    <div style={{ padding: '0 18px 120px' }}>
      <Header nav={nav} title="Tell us what's up" subtitle={`Step ${step + 1} of ${steps.length}`}/>

      {/* Progress dots */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 22 }}>
        {steps.map((s, i) => (
          <div key={s} style={{
            flex: 1, height: 4, borderRadius: 999,
            background: i <= step ? Z.gradient : Z.border, transition: 'all .3s',
          }}/>
        ))}
      </div>

      {step === 0 && (
        <div style={{ animation: 'fadeUp .3s' }}>
          <div style={{ fontSize: 19, fontWeight: 700, color: Z.text, letterSpacing: -0.3, marginBottom: 4 }}>What's the issue?</div>
          <div style={{ fontSize: 12, color: Z.text3, marginBottom: 18 }}>Pick the closest match.</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {issues.map(i => (
              <div key={i} onClick={() => setIssue(i)} style={{
                padding: 14, borderRadius: 14, cursor: 'pointer',
                background: issue === i ? 'rgba(124,58,237,0.12)' : d.panel,
                border: `1px solid ${issue === i ? Z.brand : d.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              }}>
                <span style={{ fontSize: 13.5, color: Z.text, fontWeight: 600 }}>{i}</span>
                <div style={{
                  width: 20, height: 20, borderRadius: '50%',
                  border: `2px solid ${issue === i ? Z.brand : Z.border}`,
                  background: issue === i ? Z.brand : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{issue === i && <I.check size={12} color="#fff" stroke={3}/>}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {step === 1 && (
        <div style={{ animation: 'fadeUp .3s' }}>
          <div style={{ fontSize: 19, fontWeight: 700, color: Z.text, letterSpacing: -0.3, marginBottom: 4 }}>When should they come?</div>
          <div style={{ fontSize: 12, color: Z.text3, marginBottom: 18 }}>Pick a window.</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { id: 'asap', l: 'As soon as possible', s: 'Avg arrival 18 min', pill: 'Best for urgent' },
              { id: '2h', l: 'Within 2 hours', s: 'Avg arrival 90 min', pill: null },
              { id: 'evening', l: 'This evening', s: '6 PM – 9 PM', pill: null },
              { id: 'tomorrow', l: 'Tomorrow', s: 'Pick a time', pill: null },
            ].map(o => (
              <div key={o.id} onClick={() => setWhen(o.id)} style={{
                padding: 14, borderRadius: 14, cursor: 'pointer',
                background: when === o.id ? 'rgba(124,58,237,0.12)' : d.panel,
                border: `1px solid ${when === o.id ? Z.brand : d.border}`,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
                  <span style={{ fontSize: 13.5, color: Z.text, fontWeight: 600 }}>{o.l}</span>
                  {o.pill && <Pill tone="success">{o.pill}</Pill>}
                </div>
                <div style={{ fontSize: 11, color: Z.text3 }}>{o.s}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {step === 2 && (
        <div style={{ animation: 'fadeUp .3s' }}>
          <div style={{ fontSize: 19, fontWeight: 700, color: Z.text, letterSpacing: -0.3, marginBottom: 4 }}>Any extra notes?</div>
          <div style={{ fontSize: 12, color: Z.text3, marginBottom: 18 }}>Optional — helps the pro arrive prepared.</div>
          <textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder="e.g. Sink in main kitchen, leak under counter cabinet, pipe seems loose" rows={5} style={{
            width: '100%', padding: 14, borderRadius: 14, fontFamily: Z.font, fontSize: 13.5,
            background: d.panel, border: `0.5px solid ${d.border}`, color: Z.text, outline: 'none', resize: 'none',
          }}/>
          <div style={{ fontSize: 10.5, color: Z.text4, marginTop: 8 }}>Tip: photos help even more — add on next step</div>
        </div>
      )}

      {step === 3 && (
        <div style={{ animation: 'fadeUp .3s' }}>
          <div style={{ fontSize: 19, fontWeight: 700, color: Z.text, letterSpacing: -0.3, marginBottom: 4 }}>Looks good?</div>
          <div style={{ fontSize: 12, color: Z.text3, marginBottom: 18 }}>Review before we find your pro.</div>
          <div style={{ padding: 14, borderRadius: 14, background: d.panel, border: `0.5px solid ${d.border}`, marginBottom: 14 }}>
            {[
              ['Service', svc?.name || 'Plumbing'],
              ['Issue', issue || 'Leak under sink'],
              ['When', when === 'asap' ? 'As soon as possible' : 'Today evening'],
              ['Address', "Home · Indiranagar 6th Main"],
            ].map(([l,v]) => (
              <div key={l} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', fontSize: 12.5, color: Z.text2, borderBottom: `0.5px solid ${Z.border}` }}>
                <span style={{ color: Z.text3 }}>{l}</span><span style={{ color: Z.text, fontWeight: 600 }}>{v}</span>
              </div>
            ))}
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0 0', fontSize: 12.5 }}>
              <span style={{ color: Z.text3 }}>Est. range</span><span style={{ ...mono, color: Z.text, fontWeight: 600 }}>₹450 – ₹720</span>
            </div>
          </div>
          <div style={{ padding: 12, borderRadius: 12, background: 'rgba(16,185,129,0.06)', border: `0.5px solid rgba(16,185,129,0.2)`, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
            <I.shield size={14} color={Z.success}/>
            <div style={{ fontSize: 11, color: Z.text2, lineHeight: 1.5 }}>You're not charged until <strong style={{ color: Z.text }}>after</strong> the work is done and you approve.</div>
          </div>
        </div>
      )}

      <div style={{ display: 'flex', gap: 8, marginTop: 22 }}>
        {step > 0 && <button onClick={() => setStep(s => s - 1)} style={btnGhostStyle}>Back</button>}
        <button onClick={() => {
          if (step < 3) setStep(s => s + 1);
          else nav.go('matching', { ticket: { svc, issue, when, notes } });
        }} style={{ ...btnPrimaryStyle, flex: 2 }}
        disabled={(step === 0 && !issue)}>
          {step < 3 ? 'Continue' : 'Find a pro →'}
        </button>
      </div>
    </div>
  );
};

// ── Variant 3: Chat with AI ───────────────────────────────────
const TicketChat = ({ nav, svc, dir }) => {
  const d = D(dir);
  const [msgs, setMsgs] = React.useState([
    { from: 'ai', text: `Hi Priya 👋 What's going on with the ${(svc?.name || 'plumbing').toLowerCase()}?` },
  ]);
  const [draft, setDraft] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const scriptRef = React.useRef([
    { ai: "Got it — leak under the kitchen sink. Started today, or has this been going for a while?" },
    { ai: "Thanks. Can you tell if it's coming from the pipe joint or the tap itself?", quick: ['Joint', 'Tap', 'Not sure'] },
    { ai: "Perfect, I've got enough. I'll find you an L2 plumber. Est. range ₹450–₹720, you only pay after approval.\n\nReady?", quick: ['Find a pro', 'Wait, more details'] },
    { ai: 'find' },
  ]);
  const turnRef = React.useRef(0);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, typing]);

  const send = (text) => {
    if (!text.trim()) return;
    setMsgs(m => [...m, { from: 'me', text }]);
    setDraft('');
    setTyping(true);
    setTimeout(() => {
      const next = scriptRef.current[turnRef.current++];
      setTyping(false);
      if (next?.ai === 'find') {
        nav.go('matching', { ticket: { svc, desc: text } });
      } else if (next) {
        setMsgs(m => [...m, { from: 'ai', text: next.ai, quick: next.quick }]);
      }
    }, 1100);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', position: 'relative' }}>
      <div style={{ padding: '0 18px' }}>
        <Header nav={nav} title="ZARVA Assistant" subtitle="AI · always online"/>
      </div>

      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '0 18px 16px' }}>
        {msgs.map((m, i) => (
          <div key={i} style={{
            display: 'flex', justifyContent: m.from === 'me' ? 'flex-end' : 'flex-start',
            marginBottom: 10, animation: 'fadeUp .25s',
          }}>
            <div style={{
              maxWidth: '78%', padding: '10px 14px', borderRadius: 16,
              background: m.from === 'me' ? Z.gradient : d.panel,
              border: m.from === 'me' ? 'none' : `0.5px solid ${d.border}`,
              color: Z.text, fontSize: 13.5, lineHeight: 1.5,
              boxShadow: m.from === 'me' ? `0 4px 14px ${Z.brand}44` : 'none',
              whiteSpace: 'pre-line',
            }}>{m.text}</div>
          </div>
        ))}
        {/* quick replies for last AI msg */}
        {msgs[msgs.length - 1]?.from === 'ai' && msgs[msgs.length - 1]?.quick && (
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
            {msgs[msgs.length - 1].quick.map(q => (
              <div key={q} onClick={() => send(q)} style={{
                padding: '7px 12px', borderRadius: 999, fontSize: 12, fontWeight: 600,
                background: 'rgba(124,58,237,0.12)', color: Z.brandLite,
                border: `0.5px solid rgba(124,58,237,0.35)`, cursor: 'pointer',
              }}>{q}</div>
            ))}
          </div>
        )}
        {typing && (
          <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
            <div style={{
              padding: '12px 14px', borderRadius: 16, background: d.panel,
              border: `0.5px solid ${d.border}`, display: 'flex', gap: 4,
            }}>
              {[0,1,2].map(i => <div key={i} style={{
                width: 6, height: 6, borderRadius: '50%', background: Z.brandLite,
                animation: `dotBounce 1.2s ${i*0.15}s infinite`,
              }}/>)}
            </div>
          </div>
        )}
      </div>

      <div style={{
        padding: '12px 16px 16px', borderTop: `0.5px solid ${Z.border}`,
        background: 'rgba(10,1,24,0.85)', backdropFilter: 'blur(12px)',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'rgba(124,58,237,0.16)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: Z.brandLite, border: `0.5px solid ${Z.borderStrong}` }}>
          <I.plus size={18}/>
        </div>
        <input value={draft} onChange={e => setDraft(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && send(draft)}
          placeholder="Type your message…" style={{
          flex: 1, padding: '10px 14px', borderRadius: 999,
          background: d.panel, border: `0.5px solid ${d.border}`,
          color: Z.text, fontFamily: Z.font, fontSize: 13.5, outline: 'none',
        }}/>
        <div onClick={() => send(draft || 'Yes, sink is leaking under the counter, started today, getting worse.')} style={{
          width: 40, height: 40, borderRadius: '50%', cursor: 'pointer',
          background: Z.gradient, display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff', boxShadow: `0 0 14px ${Z.brand}88`,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m22 2-7 20-4-9-9-4 20-7z"/></svg>
        </div>
      </div>
    </div>
  );
};

// Shared header
const Header = ({ nav, title, subtitle }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18, paddingTop: 4 }}>
    <div onClick={() => nav.back()} style={{
      width: 38, height: 38, borderRadius: '50%', background: 'rgba(20,8,40,0.7)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: Z.text, cursor: 'pointer', border: `0.5px solid ${Z.border}`,
    }}><I.chevL size={20}/></div>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 17, fontWeight: 700, color: Z.text, letterSpacing: -0.3 }}>{title}</div>
      {subtitle && <div style={{ fontSize: 11, color: Z.text3, marginTop: 1 }}>{subtitle}</div>}
    </div>
  </div>
);

Object.assign(window, { TicketAI, TicketGuided, TicketChat, Header });
