// Une journée avec Sofia — carousel of conversation scenes.

const CLIENT_AVATAR = (name) =>
  `https://api.dicebear.com/9.x/lorelei/svg?seed=${encodeURIComponent('client-' + name)}&backgroundColor=ebe4d6&radius=50`;

const SCENES = [
  {
    time: '06:32', marker: 'Premier message', channel: 'WhatsApp',
    exchange: [
      { from: 'client', name: 'Christine',   text: "Bonjour, j'aimerais réserver un cours de surf pour mes deux enfants samedi matin 🏄" },
      { from: 'agent',  name: 'Sofia · 4 s', text: "Bonjour Christine ! Il reste deux places samedi à 10h et trois à 11h30. Vous préférez quel créneau ? Je peux les bloquer le temps que vous confirmiez." },
    ],
    outcome: { type: 'ok', label: 'Réservation confirmée · samedi 10h' },
  },
  {
    time: '09:14', marker: 'Carnet à 80 %', channel: 'Système',
    narrative: "L’agenda du samedi est complet. Sofia ouvre automatiquement une liste d’attente et redirige les nouveaux contacts vers les créneaux du dimanche. Zéro intervention humaine.",
    outcome: { type: 'system', label: "Liste d’attente créée · 6 contacts requalifiés" },
  },
  {
    time: '11:47', marker: 'Une famille de quatre', channel: 'WhatsApp',
    exchange: [
      { from: 'client', name: 'Marc D.',     text: "Bonjour, je voudrais réserver pour mes 3 enfants : 8, 10 et 12 ans." },
      { from: 'agent',  name: 'Sofia · 2 s', text: "Bonjour Marc ! Pour les enfants j'ai samedi 9h en formule junior. Je vous envoie les trois bons d'entrée et je préviens Léa, leur monitrice ce matin-là." },
    ],
    outcome: { type: 'ok', label: '3 réservations · monitrice briefée' },
  },
  {
    time: '14:58', marker: 'Hors périmètre', channel: 'WhatsApp',
    exchange: [
      { from: 'client', name: 'Visiteur',    text: "Vous louez des combinaisons taille 12 ans ?" },
      { from: 'agent',  name: 'Sofia · 3 s', text: "Excellente question. Je transfère à Léa qui gère le matériel ; elle vous répond dans la matinée. Je lui partage tout le contexte de notre échange." },
    ],
    outcome: { type: 'escalate', label: 'Escaladé à Léa avec contexte' },
  },
  {
    time: '19:03', marker: 'Annulation tardive', channel: 'WhatsApp',
    exchange: [
      { from: 'client', name: 'Émilie',      text: "Désolée, on doit annuler demain matin, la petite est malade 😢" },
      { from: 'agent',  name: 'Sofia · 5 s', text: "Pas de souci Émilie. Le créneau est libéré et je propose à la liste d'attente. Bon rétablissement à votre fille. On reste en contact." },
    ],
    outcome: { type: 'ok', label: "Créneau réaffecté à la liste d'attente" },
  },
  {
    time: '23:48', marker: 'Dernière réservation', channel: 'WhatsApp',
    exchange: [
      { from: 'client', name: 'Paul (Berlin)', text: "Hi! We arrive tomorrow morning, can we book a surf lesson for two adults?" },
      { from: 'agent',  name: 'Sofia · 6 s',   text: "Hi Paul, welcome ! Tomorrow at 11h works for two adults. I've held the spot for 30 min. Just confirm and we're set. See you on the water." },
    ],
    outcome: { type: 'ok', label: "Réservé à minuit — le studio dort depuis 4 h" },
  },
];

const OutcomeBadge = ({ outcome }) => {
  const icon = outcome.type === 'ok' ? '✓' : outcome.type === 'escalate' ? '↻' : '◇';
  return (
    <div className={`scene__outcome scene__outcome--${outcome.type}`}>
      <span className="scene__outcome-mark">{icon}</span>
      {outcome.label}
    </div>
  );
};

const SceneBubble = ({ m }) => {
  const isAgent = m.from === 'agent';
  const cleanName = m.name.replace(/\s*·.*$/, '');
  const avatarUrl = isAgent
    ? (window.AGENT_AVATAR_URL && window.AGENT_AVATAR_URL('Sofia'))
    : CLIENT_AVATAR(cleanName);
  return (
    <div className={`scene__bubble-row scene__bubble-row--${m.from}`}>
      <span className={`scene__bubble-avatar scene__bubble-avatar--${m.from}`}>
        <img src={avatarUrl} alt={cleanName} loading="lazy" />
      </span>
      <div className={`scene__bubble scene__bubble--${m.from}`}>
        <span className="scene__bubble-from">{m.name}</span>
        {m.text}
      </div>
    </div>
  );
};

const DayWithSofia = () => {
  const [perPage, setPerPage] = React.useState(3);
  const [index, setIndex] = React.useState(0);

  React.useEffect(() => {
    const compute = () => {
      const w = window.innerWidth;
      setPerPage(w <= 640 ? 1 : w <= 980 ? 2 : 3);
    };
    compute();
    window.addEventListener('resize', compute);
    return () => window.removeEventListener('resize', compute);
  }, []);

  const maxIndex = Math.max(0, SCENES.length - perPage);
  const safeIndex = Math.min(index, maxIndex);
  const pageCount = maxIndex + 1;

  const next = () => setIndex(i => Math.min(i + 1, maxIndex));
  const prev = () => setIndex(i => Math.max(i - 1, 0));

  // translate by (100/perPage)% per index step; account for the gap visually
  // via the slide's calc() width.
  const translatePct = (100 / perPage) * safeIndex;

  return (
    <section className="day" data-screen-label="06 A day with Sofia">

      <div className="day__head">
        <div>
          <span className="b-marker"><span className="b-marker__br">[</span> 05 / Au quotidien <span className="b-marker__br">]</span></span>
          <h2 className="day__title">
            Une journée avec <em>Sofia</em>.
          </h2>
        </div>
      </div>

      <div className="day__carousel">

        <div className="day__viewport">
          <div className="day__rail" style={{ transform: `translateX(-${translatePct}%)` }}>
            {SCENES.map((s, i) => (
              <article key={i} className="day__slide">
                <div className="scene">
                  <header className="scene__head">
                    <span className="scene__time">{s.time}</span>
                    <span className="scene__rule"></span>
                    <span className="scene__marker">{s.marker}</span>
                    <span className="scene__channel">via {s.channel}</span>
                  </header>

                  <div className="scene__body">
                    {s.exchange && (
                      <div className="scene__exchange">
                        {s.exchange.map((m, j) => <SceneBubble key={j} m={m} />)}
                      </div>
                    )}
                    {s.narrative && (
                      <p className="scene__narrative">{s.narrative}</p>
                    )}
                    <OutcomeBadge outcome={s.outcome} />
                  </div>
                </div>
              </article>
            ))}
          </div>
        </div>

        <div className="day__controls">
          <button
            type="button"
            className="day__btn"
            onClick={prev}
            disabled={safeIndex === 0}
            aria-label="Précédent"
          >←</button>

          <div className="day__dots" role="tablist">
            {Array.from({ length: pageCount }).map((_, i) => (
              <button
                key={i}
                type="button"
                className={`day__dot ${i === safeIndex ? 'is-active' : ''}`}
                onClick={() => setIndex(i)}
                aria-label={`Aller à la vue ${i + 1}`}
              ></button>
            ))}
          </div>

          <button
            type="button"
            className="day__btn"
            onClick={next}
            disabled={safeIndex >= maxIndex}
            aria-label="Suivant"
          >→</button>
        </div>

      </div>

    </section>
  );
};

window.DayWithSofia = DayWithSofia;
