// ─── PHUTURISTIC v3 — Shared Components ──────────────────────────────────
// Load with <script type="text/babel" src="ph-components.jsx"></script>

// ── Primitive UI ─────────────────────────────────────────────────────────
const Ico = {
  check: () => <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  x:     () => <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  right: () => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>,
  flag:  () => <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></svg>,
  retry: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>,
  lock:  () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
  brain: () => <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96-.46 2.5 2.5 0 0 1-1.04-4.69A2.5 2.5 0 0 1 4.5 12a2.5 2.5 0 0 1 1.5-2.29A2.5 2.5 0 0 1 9.5 2z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96-.46 2.5 2.5 0 0 0 1.04-4.69A2.5 2.5 0 0 0 19.5 12a2.5 2.5 0 0 0-1.5-2.29A2.5 2.5 0 0 0 14.5 2z"/></svg>,
  clock: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
  sn:    () => <span style={{fontSize:10}}>🇸🇳</span>,
};

const Avatar = ({ initials, color, size=42 }) => (
  <div style={{ width:size, height:size, borderRadius:'50%', background:`linear-gradient(135deg,${color},${color}88)`, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:size*0.31, color:'white', flexShrink:0 }}>{initials}</div>
);
const Tag = ({ children, color }) => (
  <div style={{ display:'inline-block', marginTop:4, background:`${color}18`, color, borderRadius:20, padding:'2px 9px', fontSize:10, fontFamily:'var(--mono)' }}>{children}</div>
);
const StepLabel = ({ children, badge, style }) => (
  <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:7, ...style }}>
    <span style={{ fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.1em', color:'var(--text-muted)', textTransform:'uppercase' }}>{children}</span>
    {badge && <span style={{ background:`${badge.bg}`, color:badge.color, fontSize:9, fontFamily:'var(--mono)', padding:'2px 7px', borderRadius:20 }}>{badge.text}</span>}
  </div>
);
const Hint = ({ children }) => (
  <p style={{ fontSize:12, color:'var(--text-dim)', lineHeight:1.65, marginBottom:6 }}>{children}</p>
);
const InfoBox = ({ children, color='var(--blue)' }) => (
  <div style={{ background:`${color}0d`, border:`1px solid ${color}22`, borderRadius:9, padding:'9px 13px', fontSize:12, color:'var(--text-dim)', lineHeight:1.65 }}>{children}</div>
);
const Mono = ({ children, color, size=10, style }) => (
  <div style={{ fontFamily:'var(--mono)', fontSize:size, color, letterSpacing:'0.07em', ...style }}>{children}</div>
);
const CheckBox = ({ checked, color='var(--blue)' }) => (
  <div style={{ width:17, height:17, borderRadius:4, flexShrink:0, marginTop:1, background:checked?color:'var(--surface3)', border:`2px solid ${checked?color:'var(--border)'}`, display:'flex', alignItems:'center', justifyContent:'center', color:'white', transition:'all 0.15s' }}>
    {checked && <Ico.check />}
  </div>
);
const Radio = ({ checked, color='var(--blue)', size=21 }) => (
  <div style={{ width:size, height:size, borderRadius:'50%', flexShrink:0, background:checked?color:'var(--surface3)', border:`2px solid ${checked?color:'var(--border)'}`, display:'flex', alignItems:'center', justifyContent:'center', transition:'all 0.15s' }}>
    {checked && <div style={{ width:size*0.36, height:size*0.36, borderRadius:'50%', background:'white' }} />}
  </div>
);
const PrimaryBtn = ({ children, onClick, disabled, color='var(--blue)', style }) => (
  <button onClick={onClick} disabled={disabled} style={{ width:'100%', padding:13, borderRadius:'var(--r)', background:disabled?'var(--surface3)':color, border:'none', color:disabled?'var(--text-muted)':'white', fontSize:14, fontWeight:700, cursor:disabled?'default':'pointer', transition:'all 0.2s', boxShadow:disabled?'none':`0 4px 16px ${color}44`, display:'flex', alignItems:'center', justifyContent:'center', gap:7, ...style }}>{children}</button>
);

// ── Typewriter ────────────────────────────────────────────────────────────
const TypewriterText = ({ text, speed=18, onDone, skippable=true, style, textStyle }) => {
  const [displayed, setDisplayed] = React.useState('');
  const [done, setDone] = React.useState(false);
  const idx = React.useRef(0);
  const timer = React.useRef(null);

  const finish = React.useCallback(() => {
    clearInterval(timer.current);
    setDisplayed(text);
    setDone(true);
    onDone && onDone();
  }, [text, onDone]);

  React.useEffect(() => {
    idx.current = 0;
    setDisplayed('');
    setDone(false);
    timer.current = setInterval(() => {
      idx.current += 1;
      setDisplayed(text.slice(0, idx.current));
      if (idx.current >= text.length) { clearInterval(timer.current); setDone(true); onDone && onDone(); }
    }, speed);
    return () => clearInterval(timer.current);
  }, [text, speed]);

  return (
    <span onClick={skippable && !done ? finish : undefined} style={{ cursor: skippable&&!done?'pointer':'default', ...style }}>
      <span style={textStyle}>{displayed}</span>
      {!done && <span style={{ display:'inline-block', width:2, height:'1em', background:'currentColor', marginLeft:1, verticalAlign:'text-bottom', animation:'blink 0.7s step-end infinite', opacity:0.7 }} />}
    </span>
  );
};

// ── Forced Timer Button ────────────────────────────────────────────────────
const TimerButton = ({ seconds=12, label, onClick, color='var(--red)' }) => {
  const [rem, setRem] = React.useState(seconds);
  const [ready, setReady] = React.useState(false);
  React.useEffect(() => {
    if (rem <= 0) { setReady(true); return; }
    const t = setTimeout(() => setRem(r=>r-1), 1000);
    return () => clearTimeout(t);
  }, [rem]);
  const pct = ((seconds-rem)/seconds)*100;
  return (
    <button onClick={ready?onClick:undefined} disabled={!ready} style={{ position:'relative', overflow:'hidden', display:'flex', alignItems:'center', justifyContent:'center', gap:7, width:'100%', padding:'12px 16px', borderRadius:'var(--r)', background:ready?color:'var(--surface3)', border:`1.5px solid ${ready?color:'var(--surface4)'}`, color:ready?'white':'var(--text-muted)', fontSize:13, fontWeight:700, cursor:ready?'pointer':'default', transition:'color 0.3s, background 0.3s, border-color 0.3s' }}>
      {!ready && <div style={{ position:'absolute', left:0, top:0, height:'100%', width:`${pct}%`, background:`${color}20`, transition:'width 1s linear' }}/>}
      <span style={{ position:'relative', zIndex:1, display:'flex', alignItems:'center', gap:6 }}><Ico.retry />{ready ? label : `Lisez — ${rem}s`}</span>
    </button>
  );
};

// ── Confidence Slider ─────────────────────────────────────────────────────
const ConfidenceGate = ({ stepLabel, onConfirm }) => {
  const [val, setVal] = React.useState(null);
  const opts = [
    { id:'low',  label:'Pas sûr(e)', color:'var(--amber)', emoji:'🤔' },
    { id:'mid',  label:'Assez sûr(e)', color:'var(--blue)',  emoji:'🙂' },
    { id:'high', label:'Certain(e)',   color:'var(--green)', emoji:'💪' },
  ];
  return (
    <div style={{ background:'var(--surface2)', border:'1px solid var(--border)', borderRadius:'var(--r)', padding:16, marginBottom:14, animation:'fadeIn 0.3s ease' }}>
      <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:10 }}>
        <span style={{ color:'var(--purple)', display:'flex' }}><Ico.brain /></span>
        <span style={{ fontSize:12.5, fontWeight:600, color:'var(--text)' }}>Avant de répondre à {stepLabel}</span>
      </div>
      <p style={{ fontSize:12, color:'var(--text-dim)', lineHeight:1.6, marginBottom:12 }}>À quel point êtes-vous confiant(e) dans votre réponse ?</p>
      <div style={{ display:'flex', gap:7, marginBottom:12 }}>
        {opts.map(o => (
          <div key={o.id} onClick={() => setVal(o.id)} style={{ flex:1, padding:'9px 6px', borderRadius:9, textAlign:'center', cursor:'pointer', background:val===o.id?`${o.color}18`:'var(--surface3)', border:`1.5px solid ${val===o.id?o.color:'var(--border)'}`, transition:'all 0.15s' }}>
            <div style={{ fontSize:18, marginBottom:3 }}>{o.emoji}</div>
            <div style={{ fontSize:10.5, fontWeight: val===o.id?600:400, color:val===o.id?o.color:'var(--text-dim)', lineHeight:1.3 }}>{o.label}</div>
          </div>
        ))}
      </div>
      <PrimaryBtn onClick={() => onConfirm(val)} disabled={!val} color="var(--purple)">
        Commencer l'étape <Ico.right />
      </PrimaryBtn>
    </div>
  );
};

// ── Confidence Inline ─────────────────────────────────────────────────────
// Appears after an answer is selected, before submit. Compact 3-button picker.
const ConfidenceInline = ({ value, onChange }) => {
  const opts = [
    { id:'low',  label:'Pas sûr(e)',  color:'var(--amber)', emoji:'🤔' },
    { id:'mid',  label:'Assez sûr(e)',color:'var(--blue)',   emoji:'🙂' },
    { id:'high', label:'Certain(e)',  color:'var(--green)',  emoji:'💪' },
  ];
  return (
    <div style={{ background:'rgba(139,111,191,0.06)', border:'1.5px solid rgba(139,111,191,0.22)', borderRadius:'var(--r)', padding:'11px 12px', marginTop:10, animation:'slideUp 0.25s ease' }}>
      <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:8 }}>
        <span style={{ color:'var(--purple)', display:'flex' }}><Ico.brain /></span>
        <span style={{ fontSize:11, fontWeight:600, color:'var(--purple)', letterSpacing:'0.03em' }}>
          Votre confiance dans cette réponse ?
        </span>
      </div>
      <div style={{ display:'flex', gap:6 }}>
        {opts.map(o => (
          <div key={o.id} onClick={() => onChange(o.id)}
            style={{ flex:1, padding:'7px 4px', borderRadius:8, textAlign:'center', cursor:'pointer',
              background:value===o.id?`${o.color}18`:'var(--surface3)',
              border:`1.5px solid ${value===o.id?o.color:'var(--border)'}`,
              transition:'all 0.15s' }}>
            <div style={{ fontSize:15, marginBottom:2 }}>{o.emoji}</div>
            <div style={{ fontSize:9.5, fontWeight:value===o.id?700:400,
              color:value===o.id?o.color:'var(--text-muted)', lineHeight:1.3 }}>{o.label}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ── Feedback Card ─────────────────────────────────────────────────────────
const FeedbackCard = ({ type, title, text, consequence, earnedPts, maxPts, onContinue, onRetry, retrySeconds=12, isFirstRun=true }) => {
  const cfg = {
    correct:   { bg:'rgba(34,197,94,0.06)',  border:'rgba(34,197,94,0.22)',  accent:'#22C55E', sym:'✓' },
    acceptable:{ bg:'rgba(245,158,11,0.06)', border:'rgba(245,158,11,0.22)', accent:'#F59E0B', sym:'~' },
    critical:  { bg:'rgba(239,68,68,0.06)',  border:'rgba(239,68,68,0.28)',  accent:'#EF4444', sym:'✕' },
    info:      { bg:'rgba(59,130,246,0.06)', border:'rgba(59,130,246,0.22)', accent:'#3B82F6', sym:'→' },
  };
  const c = cfg[type]||cfg.info;
  const speeds = { correct:28, acceptable:38, critical:52, info:32 };
  const speed = speeds[type]||18;
  const [textDone, setTextDone] = React.useState(!isFirstRun);
  const [consDone, setConsDone] = React.useState(!isFirstRun || !consequence);
  const allDone = textDone && consDone;

  return (
    <div style={{ background:c.bg, border:`1px solid ${c.border}`, borderRadius:'var(--r)', padding:15, marginTop:12, animation:'slideUp 0.3s ease' }}>
      <div style={{ display:'flex', gap:10, alignItems:'flex-start', marginBottom: consequence?10:8 }}>
        <div style={{ width:22, height:22, borderRadius:'50%', background:c.accent, color:'white', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:800, flexShrink:0 }}>{c.sym}</div>
        <div style={{ flex:1 }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:5 }}>
            <span style={{ fontWeight:700, fontSize:13, color:c.accent }}>{title}</span>
            {earnedPts !== undefined && (
              <span style={{ background:'var(--blue-dim)', border:'1px solid rgba(59,130,246,0.2)', borderRadius:20, padding:'2px 8px', fontFamily:'var(--mono)', fontSize:10, color:'var(--blue)' }}>+{earnedPts}/{maxPts} pts</span>
            )}
          </div>
          <p style={{ fontSize:12.5, color:'var(--text-dim)', lineHeight:1.65 }}>
            {isFirstRun
              ? <TypewriterText text={text} speed={speed} skippable={type!=='critical'} onDone={() => setTextDone(true)} />
              : text}
          </p>
        </div>
      </div>
      {consequence && (
        <div style={{ background:'rgba(239,68,68,0.08)', border:'1px solid rgba(239,68,68,0.2)', borderRadius:8, padding:'10px 12px', marginBottom:10 }}>
          <Mono color="var(--red)" size={9} style={{marginBottom:5}}>CE QUI SE SERAIT PASSÉ</Mono>
          <p style={{ fontSize:12, color:'rgba(239,68,68,0.85)', lineHeight:1.7, fontStyle:'italic' }}>
            {isFirstRun
              ? <TypewriterText text={consequence} speed={52} skippable={false} onDone={() => setConsDone(true)} />
              : consequence}
          </p>
        </div>
      )}
      {allDone && (
        <div style={{ display:'flex', justifyContent:'flex-end', marginTop:10 }}>
          {onRetry
            ? <TimerButton seconds={retrySeconds} label="Réessayer" onClick={onRetry} color="var(--red)" />
            : onContinue && (
              <button onClick={onContinue} style={{ display:'flex', alignItems:'center', gap:6, background:'var(--teal)', border:'none', color:'#080f1e', padding:'10px 18px', borderRadius:8, fontSize:13, fontWeight:700, cursor:'pointer' }}>
                Continuer <Ico.right />
              </button>
            )}
        </div>
      )}
    </div>
  );
};

// ── Flag Modal ─────────────────────────────────────────────────────────────
const FlagModal = ({ caseId, onClose }) => {
  const [diagnosis, setDiagnosis] = React.useState('');
  const [reason, setReason] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);

  const send = async () => {
    if (!diagnosis.trim()) return;
    setSending(true);
    try {
      await fetch('https://csmgotkcifydwkdhjsck.supabase.co/rest/v1/flags', {
        method: 'POST',
        headers: {
          'apikey': 'sb_publishable_nlUeg6raQknjAxuU7cH_Lg_cd2WjSmZ',
          'Authorization': 'Bearer sb_publishable_nlUeg6raQknjAxuU7cH_Lg_cd2WjSmZ',
          'Content-Type': 'application/json',
          'Prefer': 'return=minimal'
        },
        body: JSON.stringify({
          case_id: caseId,
          diagnosis: diagnosis,
          reason: reason
        })
      });
      setSent(true);
    } catch (e) {
      alert("Erreur lors de l'envoi du signalement.");
    }
    setSending(false);
  };
  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(8,15,30,0.9)', zIndex:200, display:'flex', alignItems:'flex-end', justifyContent:'center' }} onClick={onClose}>
      <div style={{ background:'var(--surface2)', border:'1px solid var(--border2)', borderRadius:'16px 16px 0 0', padding:20, width:'100%', maxWidth:440, animation:'slideUp 0.25s ease' }} onClick={e=>e.stopPropagation()}>
        {sent ? (
          <div style={{ textAlign:'center', padding:'20px 0' }}>
            <div style={{ fontSize:26, marginBottom:8 }}>✓</div>
            <p style={{ color:'var(--green)', fontWeight:700, fontSize:14, marginBottom:4 }}>Signalement envoyé</p>
            <p style={{ color:'var(--text-muted)', fontSize:12, marginBottom:14 }}>L'équipe Phuturistic examinera votre retour.</p>
            <button onClick={onClose} style={{ background:'var(--surface3)', border:'none', color:'var(--text-dim)', padding:'8px 20px', borderRadius:8, fontSize:12, cursor:'pointer' }}>Fermer</button>
          </div>
        ) : (
          <>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
              <span style={{ color:'var(--amber)' }}><Ico.flag /></span>
              <span style={{ fontWeight:700, fontSize:14 }}>Signaler un diagnostic erroné</span>
            </div>
            <p style={{ fontSize:12, color:'var(--text-dim)', lineHeight:1.65, marginBottom:12 }}>Vous pensez que le diagnostic affiché est incorrect ? Indiquez le bon diagnostic et expliquez votre raisonnement.</p>
            <div style={{ marginBottom:9 }}>
              <Mono color="var(--text-muted)" size={9} style={{marginBottom:5}}>DIAGNOSTIC CORRECT SELON VOUS</Mono>
              <input value={diagnosis} onChange={e=>setDiagnosis(e.target.value)} placeholder="Ex: Vaginose bactérienne…" style={{ width:'100%', background:'var(--surface3)', border:'1px solid var(--border2)', borderRadius:8, padding:'9px 12px', color:'var(--text)', fontSize:13, fontFamily:'var(--font)', outline:'none' }} />
            </div>
            <div style={{ marginBottom:14 }}>
              <Mono color="var(--text-muted)" size={9} style={{marginBottom:5}}>JUSTIFICATION</Mono>
              <textarea value={reason} onChange={e=>setReason(e.target.value)} placeholder="Expliquez pourquoi…" rows={3} style={{ width:'100%', background:'var(--surface3)', border:'1px solid var(--border2)', borderRadius:8, padding:'9px 12px', color:'var(--text)', fontSize:13, fontFamily:'var(--font)', outline:'none', resize:'vertical' }} />
            </div>
            <div style={{ display:'flex', gap:8 }}>
              <button onClick={onClose} style={{ flex:1, background:'var(--surface3)', border:'1px solid var(--border)', color:'var(--text-dim)', padding:10, borderRadius:8, fontSize:13, cursor:'pointer' }}>Annuler</button>
              <button onClick={send} disabled={!diagnosis.trim() || sending} style={{ flex:2, background:diagnosis.trim()?'var(--amber)':'var(--surface3)', border:'none', color:diagnosis.trim()?'#080f1e':'var(--text-muted)', padding:10, borderRadius:8, fontSize:13, fontWeight:700, cursor:diagnosis.trim()&&!sending?'pointer':'default' }}>
                {sending ? 'Envoi...' : 'Envoyer'}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

// ── Waterfall Progress ─────────────────────────────────────────────────────
const STEP_LABELS_V3 = ["Écouter","Extraire","Questionner","Diagnostiquer","Évaluer","Traiter","Conseiller","Débrief"];

const WaterfallProgress = ({ current, done: doneSteps }) => (
  <div style={{ display:'flex', alignItems:'stretch', padding:'0 2px', gap:0 }}>
    {STEP_LABELS_V3.map((label, i) => {
      const isDone = doneSteps.includes(i);
      const isActive = current === i;
      return (
        <div key={i} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:4, position:'relative' }}>
          {i > 0 && <div style={{ position:'absolute', top: isActive?12:9, left:0, right:'50%', height:2, zIndex:0, background: isDone?'var(--green)':isActive?'var(--blue)':'var(--surface4)' }}/>}
          {i < STEP_LABELS_V3.length-1 && <div style={{ position:'absolute', top: isActive?12:9, left:'50%', right:0, height:2, zIndex:0, background: doneSteps.includes(i)?'var(--green)':'var(--surface4)' }}/>}
          <div style={{ width:isActive?24:18, height:isActive?24:18, borderRadius:'50%', zIndex:1, flexShrink:0, background:isDone?'var(--green)':isActive?'var(--blue)':'var(--surface3)', border:isActive?'3px solid rgba(59,130,246,0.3)':isDone?'2px solid var(--green)':'2px solid var(--surface4)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:isActive?'0 0 0 5px rgba(59,130,246,0.1), 0 0 14px rgba(59,130,246,0.2)':'none', transition:'all 0.3s cubic-bezier(0.34,1.56,0.64,1)' }}>
            {isDone ? <span style={{color:'white',display:'flex'}}><Ico.check /></span>
              : <span style={{ fontFamily:'var(--mono)', fontSize:isActive?9:7, fontWeight:600, color:isActive?'white':'var(--text-muted)', lineHeight:1 }}>{i}</span>}
          </div>
          <span style={{ fontSize:7, fontWeight:isActive?700:400, color:isDone?'var(--green)':isActive?'var(--blue)':'var(--text-muted)', textAlign:'center', lineHeight:1.2, whiteSpace:'nowrap' }}>{label}</span>
        </div>
      );
    })}
  </div>
);

// Export all to window
Object.assign(window, {
  Ico, Avatar, Tag, StepLabel, Hint, InfoBox, Mono,
  CheckBox, Radio, PrimaryBtn,
  TypewriterText, TimerButton, ConfidenceGate, ConfidenceInline,
  FeedbackCard, FlagModal, WaterfallProgress,
  STEP_LABELS_V3,
});
