// Résonance — F3.8 Consultation & F3.9 Harmonie Streak + Nuance de recul

const { useState: uSx, useEffect: uEx } = React;

// ═════════════════════════════════════════════════════════════
// F3.8 — Consultation card (inline in Écho)
// ═════════════════════════════════════════════════════════════
function ConsultCard({ go }) {
  const [dismissed, setDismissed] = uSx(false);
  if (dismissed) return null;

  return (
    <div style={{ marginTop: 20, position: 'relative' }}>
      {/* denser orange orb behind this card */}
      <div style={{
        position:'absolute', inset:-20, pointerEvents:'none',
        background:`radial-gradient(circle at 30% 30%, ${RZ.orange}55 0%, ${RZ.orange}00 60%)`,
        filter:'blur(30px)', zIndex:-1, borderRadius: 30,
      }}/>
      <Glass raised style={{ padding: 18 }}>
        <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom: 12 }}>
          <div style={{ width:28, height:28, borderRadius:'50%',
            background: `radial-gradient(circle at 35% 30%, ${RZ.orange}ee 0%, ${RZ.orange}50 70%)`,
            boxShadow: `0 2px 8px -2px ${RZ.orange}80`,
          }}/>
          <div style={{ fontSize: 10, fontWeight: 600, color: '#A82E1A', textTransform: 'uppercase', letterSpacing: 1 }}>
            Signal à écouter
          </div>
        </div>

        <div style={{ fontSize: 18, fontWeight: 700, color: RZ.fg1, letterSpacing: -0.2, marginBottom: 10 }}>
          Ton corps t'envoie un signal.
        </div>
        <div style={{ fontSize: 13, color: RZ.fg2, lineHeight: 1.6, marginBottom: 16 }}>
          C'est la troisième fois cette semaine que ton corps et ta voix racontent la fatigue. Ce n'est pas une urgence, mais c'est un bon moment pour en parler à quelqu'un de qualifié.
        </div>
        <div style={{ fontSize: 12, color: RZ.fg3, fontStyle:'italic', lineHeight: 1.5, marginBottom: 16 }}>
          Pas d'obligation. Juste une porte ouverte.
        </div>

        <div style={{ fontSize: 10, fontWeight: 600, color: RZ.fg3, textTransform:'uppercase', letterSpacing: 1, marginBottom: 10 }}>
          Trois pistes équivalentes
        </div>

        <div style={{ display:'grid', gap: 8, marginBottom: 14 }}>
          <ConsultPath icon="🩺" title="Médecin du sport" desc="Un regard médical sur ce que ton corps raconte"/>
          <ConsultPath icon="🧘" title="Ostéopathe ou kiné" desc="Libérer les tensions physiques qui s'accumulent"/>
          <ConsultPath icon="💬" title="Coach ou préparateur mental" desc="Mettre des mots sur la charge mentale"/>
        </div>

        <PrimaryBtn onClick={() => go('F38_Consult')}>Trouver un praticien</PrimaryBtn>
        <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
          <button onClick={() => setDismissed(true)} style={{
            flex: 1, padding: '12px', borderRadius: 14, background: 'rgba(255,255,255,0.5)',
            border: '1px solid rgba(24,20,15,0.08)', fontSize: 13, fontWeight: 500, color: RZ.fg1, cursor: 'pointer',
          }}>Plus tard</button>
        </div>
        <div onClick={() => go('F38_OptOut')} style={{
          textAlign:'center', marginTop: 10, fontSize: 11, color: RZ.fg3, cursor: 'pointer', textDecoration: 'underline',
        }}>Ne plus me suggérer</div>
      </Glass>
    </div>
  );
}

function ConsultPath({ icon, title, desc }) {
  return (
    <div style={{
      display:'flex', alignItems:'flex-start', gap: 12, padding: 12,
      background: 'rgba(255,255,255,0.4)', borderRadius: 12,
      border: '1px solid rgba(255,255,255,0.5)',
    }}>
      <div style={{ fontSize: 22, lineHeight: 1, marginTop: 2 }}>{icon}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: RZ.fg1, marginBottom: 2 }}>{title}</div>
        <div style={{ fontSize: 12, color: RZ.fg2, lineHeight: 1.45 }}>{desc}</div>
      </div>
    </div>
  );
}

// F3.8 — Detail screen: the 3 paths + external redirect state
function F38_Consult({ go }) {
  const [selected, setSelected] = uSx(null);
  const paths = [
    { id: 'md',   icon: '🩺', title: 'Médecin du sport',        desc: 'Un regard médical sur ce que ton corps raconte', link: 'Doctolib · Médecine du sport' },
    { id: 'osteo', icon: '🧘', title: 'Ostéopathe ou kiné',      desc: 'Libérer les tensions physiques qui s\'accumulent', link: 'Doctolib · Ostéopathie & Kinésithérapie' },
    { id: 'coach', icon: '💬', title: 'Coach ou préparateur mental', desc: 'Mettre des mots sur la charge mentale',        link: 'Annuaire · SFP — Sport & Préparation mentale' },
  ];
  return (
    <Screen intent="result-alerte">
      <TopBar onBack={() => go('S13_Echo')}/>
      <div style={{ padding: '0 20px 60px' }}>
        <div style={{ fontSize: 24, fontWeight: 700, color: RZ.fg1, letterSpacing: -0.3, marginBottom: 8 }}>
          Trois pistes, à égalité.
        </div>
        <div style={{ fontSize: 13, color: RZ.fg2, lineHeight: 1.55, marginBottom: 24 }}>
          Choisis ce qui résonne pour toi. Je ne recommande personne en particulier — je te redirige vers un annuaire neutre.
        </div>

        {paths.map(p => (
          <Glass key={p.id} raised={selected === p.id} onClick={() => setSelected(p.id)} style={{
            padding: 16, marginBottom: 10, cursor: 'pointer',
            transform: selected === p.id ? 'scale(1.01)' : 'scale(1)', transition: 'transform 180ms ease',
          }}>
            <div style={{ display:'flex', gap: 14, alignItems: 'flex-start' }}>
              <div style={{ fontSize: 28, lineHeight: 1 }}>{p.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 600, color: RZ.fg1, marginBottom: 4 }}>{p.title}</div>
                <div style={{ fontSize: 12, color: RZ.fg2, lineHeight: 1.45, marginBottom: 8 }}>{p.desc}</div>
                {selected === p.id && (
                  <div style={{ marginTop: 10, padding: '10px 12px', background: 'rgba(24,20,15,0.04)', borderRadius: 10, display: 'flex', alignItems:'center', gap: 8, animation: 'rz-slide-up 200ms ease-out' }}>
                    <Icon name="arrowRight" size={13} color={RZ.mauve}/>
                    <span style={{ fontSize: 12, color: RZ.fg1, flex: 1 }}>{p.link}</span>
                    <span style={{ fontSize: 10, color: RZ.fg3, textTransform: 'uppercase', letterSpacing: 0.6 }}>Externe</span>
                  </div>
                )}
              </div>
            </div>
          </Glass>
        ))}

        <PrimaryBtn onClick={() => go('S13_Echo')} disabled={!selected} style={{ marginTop: 16 }}>
          {selected ? 'Ouvrir l\'annuaire' : 'Choisis une piste'}
        </PrimaryBtn>

        <div style={{ marginTop: 20, padding: 14, background: 'rgba(24,20,15,0.04)', borderRadius: 12 }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: RZ.fg3, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6 }}>Ce que je ne fais pas</div>
          <div style={{ fontSize: 11.5, color: RZ.fg2, lineHeight: 1.6 }}>
            Pas de diagnostic. Pas de score médical. Pas de praticien nommé. Aucun partenariat rémunéré.
          </div>
        </div>
      </div>
    </Screen>
  );
}

// F3.8 — Opt-out confirmation
function F38_OptOut({ go }) {
  const [done, setDone] = uSx(false);
  return (
    <Screen intent="settings">
      <TopBar onBack={() => go('S13_Echo')}/>
      <div style={{ padding: '40px 24px', textAlign: 'center', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', height: 'calc(100% - 80px)' }}>
        {!done ? (
          <>
            <div style={{ width: 72, height: 72, borderRadius: 24, background: 'rgba(24,20,15,0.06)', display:'flex', alignItems:'center', justifyContent:'center', marginBottom: 24 }}>
              <Icon name="lock" size={30}/>
            </div>
            <div style={{ fontSize: 20, fontWeight: 700, color: RZ.fg1, letterSpacing: -0.3, marginBottom: 12 }}>Ne plus recevoir<br/>ces suggestions ?</div>
            <div style={{ fontSize: 13, color: RZ.fg2, lineHeight: 1.6, marginBottom: 28, maxWidth: 280 }}>
              Je ne te proposerai plus de consulter. Tu pourras réactiver cette option à tout moment dans les Paramètres.
            </div>
            <PrimaryBtn onClick={() => setDone(true)} style={{ maxWidth: 280 }}>Désactiver les suggestions</PrimaryBtn>
            <GhostBtn onClick={() => go('S13_Echo')} style={{ marginTop: 6 }}>Annuler</GhostBtn>
          </>
        ) : (
          <>
            <div style={{ margin: '0 auto 24px' }}><NuanceViz state="equilibre" size={140}/></div>
            <div style={{ fontSize: 18, fontWeight: 600, color: RZ.fg1, marginBottom: 10 }}>C'est fait.</div>
            <div style={{ fontSize: 13, color: RZ.fg2, lineHeight: 1.55, maxWidth: 280, marginBottom: 20 }}>
              Tu restes maître. Je continue à veiller en silence.
            </div>
            <GhostBtn onClick={() => go('S13_Echo')}>Retour à Écho</GhostBtn>
          </>
        )}
      </div>
    </Screen>
  );
}

// ═════════════════════════════════════════════════════════════
// F3.9 — Harmonie Streak celebration card (inline in Écho)
// ═════════════════════════════════════════════════════════════
function StreakCard({ go }) {
  return (
    <div style={{ marginTop: 20, position: 'relative' }}>
      <div style={{
        position:'absolute', inset:-24, pointerEvents:'none',
        background:`radial-gradient(circle at 50% 40%, ${RZ.mauve}66 0%, ${RZ.mauve}00 65%)`,
        filter:'blur(40px)', zIndex:-1, borderRadius: 30,
      }}/>
      <Glass raised style={{ padding: 22, textAlign: 'center' }}>
        <div style={{ margin: '0 auto 14px', width: 120, height: 120, position: 'relative' }}>
          {/* Breathing mauve orb — homage, pas trophée */}
          <div style={{
            position: 'absolute', inset: 0, borderRadius: '50%',
            background: `radial-gradient(circle at 40% 35%, ${RZ.mauve}ee 0%, ${RZ.mauve}60 55%, ${RZ.mauve}10 100%)`,
            filter: 'blur(1px)',
            animation: 'rz-breath 4s ease-in-out infinite',
            boxShadow: `0 10px 40px -8px ${RZ.mauve}70, inset 0 0 20px rgba(255,255,255,0.3)`,
          }}/>
          {/* five faint dots as an implicit, non-gamified counter */}
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}>
            {[0,1,2,3,4].map(i => (
              <div key={i} style={{
                width: 5, height: 5, borderRadius: '50%',
                background: 'rgba(255,255,255,0.85)',
              }}/>
            ))}
          </div>
        </div>

        <div style={{ fontSize: 10, fontWeight: 600, color: RZ.mauve, textTransform: 'uppercase', letterSpacing: 1.4, marginBottom: 8 }}>
          Un moment à noter
        </div>
        <div style={{ fontSize: 22, fontWeight: 700, color: RZ.fg1, letterSpacing: -0.3, marginBottom: 10, textWrap: 'balance' }}>
          Cinq jours en Harmonie.
        </div>
        <div style={{ fontSize: 13, color: RZ.fg2, lineHeight: 1.6, marginBottom: 16, textAlign: 'left' }}>
          Ton corps et ta voix s'accordent depuis le début de la semaine. Prends un instant pour savourer — et peut-être comprendre ce qui a fonctionné.
        </div>
        <div style={{ fontSize: 12, color: RZ.fg3, lineHeight: 1.6, fontStyle: 'italic', marginBottom: 18, textAlign: 'left' }}>
          Les bonnes périodes méritent qu'on s'y arrête autant que les difficiles.
        </div>

        <PrimaryBtn onClick={() => go('F39_Recul')}>Déposer une nuance de recul</PrimaryBtn>
        <GhostBtn onClick={() => go('S13_Echo')} style={{ marginTop: 6 }}>Merci, je continue</GhostBtn>
      </Glass>
    </div>
  );
}

// F3.9 — Nuance de recul (vocal, question préparée par l'IA)
const RECUL_QUESTIONS = [
  "Qu'est-ce qui, selon toi, a nourri cette période ?",
  "Y a-t-il un rituel que tu aimerais garder ?",
  "Qu'est-ce qui pourrait fragiliser cet équilibre ?",
];

function F39_Recul({ go }) {
  const [rec, setRec] = uSx(false);
  const [t, setT] = uSx(0);
  const qIdx = 0; // could cycle; brief leaves AI choice
  const q = RECUL_QUESTIONS[qIdx];

  uEx(() => {
    if (!rec) return;
    const id = setInterval(() => setT(x => x + 0.1), 100);
    return () => clearInterval(id);
  }, [rec]);

  const mm = Math.floor(t / 60).toString().padStart(1, '0');
  const ss = Math.floor(t % 60).toString().padStart(2, '0');

  return (
    <Screen intent="result-resonance">
      <TopBar onBack={() => go('S13_Echo')}/>
      <div style={{ padding: '10px 24px 40px', height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontSize: 10, fontWeight: 600, color: RZ.mauve, textTransform: 'uppercase', letterSpacing: 1.4, marginBottom: 10 }}>
          Nuance de recul
        </div>
        <div style={{ fontSize: 14, color: RZ.fg2, lineHeight: 1.55, marginBottom: 8 }}>
          Une question préparée pour toi :
        </div>
        <div style={{ fontSize: 24, fontWeight: 600, color: RZ.fg1, letterSpacing: -0.3, lineHeight: 1.35, marginBottom: 30, textWrap: 'balance' }}>
          « {q} »
        </div>

        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
          {/* Breathing mauve button */}
          {rec && [0, 0.4, 0.8].map(d => (
            <div key={d} style={{
              position:'absolute', width: 180, height: 180, borderRadius:'50%',
              border:`2px solid ${RZ.mauve}`,
              animation: `rz-pulse-ring 2.4s ease-out ${d}s infinite`,
              opacity: 0.5,
            }}/>
          ))}
          <button onClick={() => setRec(r => !r)} style={{
            width: 140, height: 140, borderRadius: '50%',
            background: `radial-gradient(circle at 40% 35%, ${RZ.mauve}ee 0%, ${RZ.mauve}70 100%)`,
            boxShadow: `0 12px 30px -10px ${RZ.mauve}90, inset 0 0 18px rgba(255,255,255,0.35)`,
            display:'flex', alignItems:'center', justifyContent:'center',
            animation: rec ? 'none' : 'rz-breath 4s ease-in-out infinite',
            border: 'none', cursor: 'pointer',
          }}>
            <Icon name={rec ? 'pause' : 'mic'} size={44} color="#fff"/>
          </button>
        </div>

        <div style={{ textAlign:'center', fontSize: 28, fontWeight: 600, color: RZ.fg1, letterSpacing: -0.5, fontVariantNumeric: 'tabular-nums', marginTop: 10 }}>
          {mm}:{ss}
        </div>
        <div style={{ textAlign:'center', fontSize: 12, color: RZ.fg3, marginTop: 4, marginBottom: 20 }}>
          {rec ? 'Je t\'écoute.' : 'Appuie quand tu es prêt·e.'}
        </div>

        <SecondaryBtn onClick={() => go('S11_Nuance')}>{rec ? 'Terminer' : 'Plus tard'}</SecondaryBtn>
      </div>
    </Screen>
  );
}

Object.assign(window, { ConsultCard, StreakCard, F38_Consult, F38_OptOut, F39_Recul });
