/* Rinus hero, coach conversacional.
   Izquierda: una ventana de chat que avanza lento. Rinus saluda a María y le
   resume el mes en un componente con gráfico; ella agradece y pregunta cómo
   mejorar; Rinus piensa (3 puntos) y recomienda una acción para reactivar
   clientas con una promo. La acción es clickeable y se auto-acepta a los 5s.
   Derecha: el teléfono de María, que refleja el feedback en vivo. */

const { useState, useEffect, useRef, useCallback } = React;

const INIT = { ventas: 11, actividad: 78, racha: 4, meta: 62 };

const ACTIONS = [
  { tag: "Reactivación", icon: "promos",   title: "Ofrecé un 2×1 a tus 5 clientas dormidas",     desc: "Sin comprarte hace 3 semanas",        doneLabel: "Promo enviada a 5 clientas" },
  { tag: "Recompra",     icon: "catalogo", title: "Mandá el catálogo nuevo a tus 8 clientas top", desc: "Te compraron el mes pasado",           doneLabel: "Catálogo enviado a 8 clientas" },
  { tag: "Prospección",  icon: "clientes", title: "Pediles una referida a tus 3 mejores clientas", desc: "Sumá clientas nuevas por recomendación", doneLabel: "3 pedidos de referida enviados" },
];

const BEATS = [
  { type: "rinus", text: "¡Hola, María! 👋 Así venís este mes:" },
  { type: "summary" },
  { type: "user",  text: "¡Gracias! 🙌" },
  { type: "user",  text: "¿Qué puedo hacer para vender más?" },
  { type: "rinus", think: true, text: "Tenés 5 clientas que no te compran hace 3 semanas. Reactivalas con una promo:" },
  { type: "action", ai: 0 },
  { type: "rinus", think: true, text: "¡Genial! Ahora asegurá la recompra de las que ya te compraron:" },
  { type: "action", ai: 1 },
  { type: "rinus", think: true, text: "Y sumá clientas nuevas pidiendo una recomendación:" },
  { type: "action", ai: 2 },
  { type: "rinus", think: true, text: "¡Listo! Tres jugadas para cerrar la semana más fuerte 🔥" },
];

const TYPE_MS = 44;
const PAUSE_TEXT = 780;
const PAUSE_SUMMARY = 1600;
const THINK_MS = 2400;
const AUTO_MS = 8000;
const LOADING_MS = 1250;
const DONE_MS = 1550;
const LOOP_MS = 4800;

/* ── Rinus mark (logo real, el mismo del navbar, sin caja) ─────── */
function RinusMark({ size = 40 }) {
  return <img src="rinus-logo.png" width={size} height={size} alt="" aria-hidden="true" style={{ display: "block" }} />;
}

const Check = ({ s = 13, w = 3.1 }) => (
  <svg viewBox="0 0 24 24" width={s} height={s} fill="none" stroke="currentColor" strokeWidth={w} strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5 11-11" /></svg>
);

/* ── Confetti burst ────────────────────────────────────────────── */
function Confetti({ id }) {
  const bits = [];
  const colors = ["#E8613C", "#2D5442", "#4A7860", "#B8421F", "#7CA892"];
  for (let i = 0; i < 14; i++) {
    const ang = (i / 14) * Math.PI * 2 + (id % 3);
    const dist = 46 + (i % 4) * 12;
    bits.push({ x: Math.cos(ang) * dist, y: Math.sin(ang) * dist - 10, c: colors[i % colors.length], d: (i % 5) * 40 });
  }
  return (
    <div className="coach-confetti" key={id}>
      {bits.map((b, i) => (
        <span key={i} style={{ "--cx": b.x + "px", "--cy": b.y + "px", background: b.c, animationDelay: b.d + "ms" }} />
      ))}
    </div>
  );
}

/* ── Progress ring ─────────────────────────────────────────────── */
function Ring({ pct }) {
  const R = 30, C = 2 * Math.PI * R;
  return (
    <svg width="76" height="76" viewBox="0 0 76 76" className="coach-ring">
      <circle cx="38" cy="38" r={R} fill="none" stroke="var(--line-strong)" strokeWidth="6" />
      <circle cx="38" cy="38" r={R} fill="none" stroke="var(--signal)" strokeWidth="6"
        strokeLinecap="round" strokeDasharray={C}
        strokeDashoffset={C * (1 - pct / 100)}
        transform="rotate(-90 38 38)"
        style={{ transition: "stroke-dashoffset 0.9s cubic-bezier(0.2,0.8,0.2,1)" }} />
      <text x="38" y="36" textAnchor="middle" fontFamily="var(--font-display)" fontSize="17" fontWeight="700" fill="var(--ink)">{pct}%</text>
      <text x="38" y="48" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="6.5" letterSpacing="0.1em" fill="var(--ink-subtle)">A TU META</text>
    </svg>
  );
}

function StatChip({ icon, value, label, hot }) {
  return (
    <div className={"coach-chip" + (hot ? " is-hot" : "")}>
      <span className="coach-chip-ico">{icon}</span>
      <div>
        <div className="coach-chip-v">{value}</div>
        <div className="coach-chip-l">{label}</div>
      </div>
    </div>
  );
}

const MENU = [
  { name: "catalogo", label: "Catálogo" },
  { name: "promos",   label: "Promos" },
  { name: "clientes", label: "Clientes" },
  { name: "formacion",label: "Formación" },
  { name: "redes",    label: "Redes" },
  { name: "ranking",  label: "Ranking" },
];
const MenuIcon = ({ name }) => {
  switch (name) {
    case "catalogo": return <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="4" width="7" height="7" rx="1.5"/><rect x="4" y="13" width="7" height="7" rx="1.5"/><rect x="13" y="13" width="7" height="7" rx="1.5"/></svg>;
    case "promos": return <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M8.5 8.5h.01M15.5 15.5h.01M15 9l-6 6"/><path d="M4 12l2.2-2.2a2 2 0 0 0 .58-1.4V6a2 2 0 0 1 2-2h2.4a2 2 0 0 0 1.4-.58L16 1.2"/><path d="M20 12l-2.2 2.2a2 2 0 0 0-.58 1.4V18a2 2 0 0 1-2 2h-2.4a2 2 0 0 0-1.4.58L8 22.8"/></svg>;
    case "clientes": return <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3"/><path d="M4 20a5 5 0 0 1 10 0"/><path d="M16 6.5a3 3 0 0 1 0 5.5"/><path d="M18 20a5 5 0 0 0-3-4.6"/></svg>;
    case "formacion": return <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 4 2.5 9 12 14l9.5-5z"/><path d="M6.5 11.5V16c0 1.4 2.5 2.5 5.5 2.5s5.5-1.1 5.5-2.5v-4.5"/><path d="M21.5 9v5"/></svg>;
    case "redes": return <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="6" cy="12" r="2.6"/><circle cx="17" cy="6" r="2.6"/><circle cx="17" cy="18" r="2.6"/><path d="M8.3 10.8 14.7 7.2M8.3 13.2 14.7 16.8"/></svg>;
    default: return <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M8 21h8M12 17v4"/><path d="M6 4h12v4a6 6 0 0 1-12 0z"/><path d="M6 6H3.5v1.5A3 3 0 0 0 6 10M18 6h2.5v1.5A3 3 0 0 1 18 10"/></svg>;
  }
};

/* ── Resumen del mes: mini gráfico compacto + métricas (salvia + naranja) ─── */
function SummaryCard() {
  const bars = [34, 52, 44, 68, 58, 82, 100];
  const days = ["S1", "S2", "S3", "S4", "S5", "S6", "S7"];
  const metrics = [
    { k: "$ generado",   v: "$8.4k", d: "▲ +18%",       up: true },
    { k: "Ventas · mes", v: "11",    d: "62% a la meta", up: false },
    { k: "Ticket prom.", v: "$760",  d: "▲ +6%",         up: true },
  ];
  return (
    <div className="coach-summary">
      <div className="coach-summary-h"><span>Ventas · últimas semanas</span><span className="cs-day">Día 12</span></div>
      <div className="cs-body">
        <div className="cs-chart" aria-hidden="true">
          {bars.map((h, i) => {
            const hot = i === bars.length - 1;
            return (
              <div key={i} className="cs-col">
                <div className="cs-bar-wrap">
                  {hot && <span className="cs-delta">+29%</span>}
                  <div className={"cs-bar" + (hot ? " is-hot" : "")}
                    style={{ height: h + "%", opacity: hot ? 1 : (0.38 + i * 0.09), animationDelay: (i * 60) + "ms" }} />
                </div>
                <span className="cs-x">{days[i]}</span>
              </div>
            );
          })}
        </div>
        <div className="cs-metrics">
          {metrics.map((m) => (
            <div key={m.k} className="cs-metric">
              <span className="cs-metric-k">{m.k}</span>
              <b className="cs-metric-v">{m.v}</b>
              <span className={"cs-metric-d" + (m.up ? " up" : "")}>{m.d}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function HeroCoach() {
  const rootRef = useRef(null);
  const [started, setStarted] = useState(false);
  const [revealed, setRevealed] = useState(0);
  const [typed, setTyped] = useState(0);
  const [thoughtReady, setThoughtReady] = useState(false);
  const [aPhase, setAPhase] = useState("idle"); // idle | type | wait | loading | done
  const [stats, setStats] = useState(INIT);
  const [fx, setFx] = useState(null);
  const [burst, setBurst] = useState(0);

  const reset = useCallback(() => {
    setRevealed(0); setTyped(0); setThoughtReady(false); setAPhase("idle"); setStats(INIT); setFx(null);
  }, []);

  const applyFeedback = useCallback((ai) => {
    if (ai === 0) setStats((s) => ({ ...s, ventas: 12, actividad: 88, meta: 68 }));
    else if (ai === 1) setStats((s) => ({ ...s, ventas: 13, actividad: 92, meta: 78 }));
    else setStats((s) => ({ ...s, ventas: 14, actividad: 96, racha: 6, meta: 88 }));
    setFx("hit");
    setBurst((b) => b + 1);
  }, []);

  // Arranca recién cuando el bloque entra en viewport (tras scrollear un poco)
  useEffect(() => {
    const el = rootRef.current;
    if (!el) return;
    if (!("IntersectionObserver" in window)) { setStarted(true); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setStarted(true); io.disconnect(); } });
    }, { threshold: 0.3, rootMargin: "0px 0px -25% 0px" });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Driver de texto/resumen (la acción la maneja el bloque de abajo)
  useEffect(() => {
    if (!started) return;
    const beat = BEATS[revealed];
    if (!beat) { const t = setTimeout(reset, LOOP_MS); return () => clearTimeout(t); }
    if (beat.type === "action") return;
    if (beat.type === "summary") { const t = setTimeout(() => setRevealed((r) => r + 1), PAUSE_SUMMARY); return () => clearTimeout(t); }
    if (beat.type === "rinus" && beat.think && !thoughtReady) {
      const t = setTimeout(() => setThoughtReady(true), THINK_MS);
      return () => clearTimeout(t);
    }
    if (typed < beat.text.length) { const t = setTimeout(() => setTyped((c) => c + 1), TYPE_MS); return () => clearTimeout(t); }
    const t = setTimeout(() => { setRevealed((r) => r + 1); setTyped(0); setThoughtReady(false); }, PAUSE_TEXT);
    return () => clearTimeout(t);
  }, [started, revealed, typed, thoughtReady, reset]);

  // Entrada al beat de acción
  useEffect(() => {
    if (!started) return;
    if (BEATS[revealed] && BEATS[revealed].type === "action" && aPhase === "idle") { setTyped(0); setAPhase("type"); }
  }, [started, revealed, aPhase]);

  // Tipeo del título de la acción
  useEffect(() => {
    const b = BEATS[revealed];
    if (!(b && b.type === "action") || aPhase !== "type") return;
    const full = ACTIONS[b.ai].title;
    if (typed < full.length) { const t = setTimeout(() => setTyped((c) => c + 1), TYPE_MS); return () => clearTimeout(t); }
    const t = setTimeout(() => setAPhase("wait"), 220);
    return () => clearTimeout(t);
  }, [revealed, aPhase, typed]);

  useEffect(() => {
    if (aPhase !== "wait") return;
    const t = setTimeout(() => setAPhase("loading"), AUTO_MS);
    return () => clearTimeout(t);
  }, [aPhase]);

  useEffect(() => {
    if (aPhase !== "loading") return;
    const b = BEATS[revealed];
    const t = setTimeout(() => { applyFeedback(b && b.ai); setAPhase("done"); }, LOADING_MS);
    return () => clearTimeout(t);
  }, [aPhase, revealed, applyFeedback]);

  useEffect(() => {
    if (aPhase !== "done") return;
    const t = setTimeout(() => { setRevealed((r) => r + 1); setTyped(0); setThoughtReady(false); setAPhase("idle"); setFx(null); }, DONE_MS);
    return () => clearTimeout(t);
  }, [aPhase]);

  const accept = () => {
    const b = BEATS[revealed];
    if (!b || b.type !== "action") return;
    if (aPhase === "type" || aPhase === "wait") { setTyped(ACTIONS[b.ai].title.length); setAPhase("loading"); }
  };

  const curBeat = BEATS[revealed];
  const live = aPhase === "loading" || aPhase === "done";
  // La tarjeta "Próxima acción" del teléfono solo existe mientras hay una acción
  // sugerida en el chat: aparece con la acción (show), corre la barra al aceptarla
  // (progress) y festeja al terminar (success -> toast que se va).
  let boxState = null, boxTitle = "", boxDone = "";
  if (curBeat && curBeat.type === "action") {
    const A = ACTIONS[curBeat.ai];
    boxTitle = A.title; boxDone = A.doneLabel;
    // aparece recién cuando terminó de tipear (fase "wait"), no durante el tipeo
    boxState = aPhase === "loading" ? "progress"
      : aPhase === "done" ? "success"
      : aPhase === "wait" ? "show"
      : null;
  }

  const renderActionBeat = (active, ai) => {
    const A = ACTIONS[ai];
    const done = aPhase === "done" || !active;
    const p = done ? "done" : aPhase;
    const shownTitle = (active && p === "type") ? A.title.slice(0, typed) : A.title;
    return (
      <div className="coach-msg coach-msg-action" key={"action" + ai}>
        <button type="button" className={"coach-focus is-" + p}
          onClick={active ? accept : undefined}
          disabled={done || p === "loading"}>
          <span className="coach-circle">
            {done ? <Check s={22} w={2.6} />
              : p === "loading" ? <span className="coach-spinner" />
              : <span className="coach-circle-ico"><MenuIcon name={A.icon} /></span>}
            {p === "wait" && <span className="coach-attn" aria-hidden="true" />}
          </span>
          <span className="coach-focus-body">
            <span className="coach-focus-tag">{A.tag}</span>
            <span className="coach-focus-title">
              <span className="cft-ghost" aria-hidden="true">{A.title}</span>
              <span className="cft-real">{shownTitle}{active && p === "type" && <span className="coach-caret on" />}</span>
            </span>
            {done
              ? <span className="coach-focus-feedback"><span className="coach-fb-dot" />{A.doneLabel}</span>
              : <span className="coach-focus-desc">{A.desc}</span>}
          </span>
          <span className={"coach-focus-go" + (done ? " is-done" : "")}>
            {done ? <>Aceptada <Check s={12} w={3.2} /></>
              : p === "loading" ? "Enviando…"
              : <>Aceptar <span className="arrow">→</span></>}
          </span>
        </button>
      </div>
    );
  };

  const renderBeat = (beat, i) => {
    const active = i === revealed;
    if (beat.type === "summary") {
      return <div className="coach-msg coach-msg-action" key="summary"><SummaryCard /></div>;
    }
    if (beat.type === "action") return renderActionBeat(active, beat.ai);
    // pensando: solo los 3 puntos naranjas, sin globo
    if (beat.type === "rinus" && beat.think && active && !thoughtReady) {
      return (
        <div className="coach-msg is-rinus coach-msg-think" key={i}>
          <div className="coach-typing"><span /><span /><span /></div>
        </div>
      );
    }
    const text = active ? beat.text.slice(0, typed) : beat.text;
    const typing = active && typed < beat.text.length && (!beat.think || thoughtReady);
    return (
      <div className={"coach-msg is-" + beat.type} key={i}>
        {beat.type === "rinus" && <span className="coach-msg-dot" aria-hidden="true" />}
        <div className="coach-msg-bubble">{text}{typing && <span className="coach-caret on" />}</div>
      </div>
    );
  };

  return (
    <div className={"coach" + (started ? " is-in" : "")} ref={rootRef}>
      {/* ── Ventana de chat ── */}
      <div className="coach-left">
        <div className="coach-chat-head">
          <div className="coach-head-logo"><RinusMark size={34} /></div>
          <div className="coach-chat-id">
            <div className="coach-name">Rinus</div>
          </div>
        </div>

        <div className="coach-chat">
          {started && BEATS.slice(0, revealed + 1).map((b, i) => renderBeat(b, i))}
        </div>
      </div>

      {/* ── Teléfono (refleja el feedback) ── */}
      <div className="coach-right">
        <div className="coach-phone">
          <div className="coach-notch" />
          <div className="coach-statusbar">
            <span>9:41</span>
            <span className="coach-sb-icons">
              <svg viewBox="0 0 20 12" width="17" height="10"><rect x="0" y="7" width="3" height="5" rx="1" fill="currentColor"/><rect x="4.5" y="4.5" width="3" height="7.5" rx="1" fill="currentColor"/><rect x="9" y="2" width="3" height="10" rx="1" fill="currentColor"/><rect x="13.5" y="0" width="3" height="12" rx="1" fill="currentColor" opacity="0.35"/></svg>
              <svg viewBox="0 0 24 12" width="20" height="10"><rect x="0.5" y="1" width="19" height="10" rx="3" fill="none" stroke="currentColor" strokeWidth="1.2"/><rect x="2" y="2.5" width="14" height="7" rx="1.5" fill="currentColor"/><rect x="20.5" y="4" width="1.8" height="4" rx="1" fill="currentColor"/></svg>
            </span>
          </div>

          <div className="coach-screen">
            <div className="coach-greet">
              <div className="coach-greet-av">M</div>
              <div>
                <div className="coach-greet-hi">Hola, María 👋</div>
                <div className="coach-greet-sub">Día 12</div>
              </div>
            </div>

            <div className="coach-hero-stat">
              <Ring pct={stats.meta} />
              <div className="coach-hero-copy">
                <div className="coach-hero-k">Progreso del mes</div>
                <div className="coach-hero-v">Vas <b>{stats.ventas}</b> ventas</div>
                <div className="coach-hero-d">Te faltan {Math.max(0, 15 - stats.ventas)} para tu meta</div>
              </div>
            </div>

            <div className="coach-chips">
              <StatChip icon="⭐" value={stats.ventas} label="Ventas" hot={!!fx} />
              <StatChip icon="📈" value={stats.actividad + "%"} label="Actividad" hot={!!fx} />
              <StatChip icon="🔥" value={stats.racha} label="Racha" hot={!!fx} />
            </div>

            <div className="coach-menu">
              {MENU.map((m) => (
                <button key={m.name} type="button" className="coach-menu-btn">
                  <span className="coach-menu-ico"><MenuIcon name={m.name} /></span>{m.label}
                </button>
              ))}
            </div>

            {boxState && (
              <div className={"coach-next is-" + boxState} key={"box-" + curBeat.ai}>
                {boxState === "success" ? (
                  <>
                    <div className="coach-next-h"><span className="coach-next-badge is-ok">✓ Éxito</span></div>
                    <div className="coach-next-title">{boxDone}</div>
                  </>
                ) : (
                  <>
                    <div className="coach-next-h"><span className="coach-next-badge">Próxima acción</span></div>
                    <div className="coach-next-title">{boxTitle}</div>
                    {boxState === "progress" && <div className="coach-next-bar"><span /></div>}
                  </>
                )}
              </div>
            )}

            {burst > 0 && fx && <Confetti id={burst} />}
          </div>
        </div>
      </div>
    </div>
  );
}

window.HeroCoach = HeroCoach;
