// Widgets interactivos: cinta de cabeza, verificador de teléfono,
// lista previa, mini quiz, FAQ.
const { useState, useEffect, useRef } = React;

/* ---------- Diagrama de la cinta (formas simples) ---------- */
const STRAP_CHIPS = [
  "A la altura de los ojos",
  "Cámara hacia abajo — manos a la vista",
  "Firme: sin rebotes ni giros",
  "REC · horizontal · lente limpio",
];

function StrapDiagram({ step }) {
  // step: 0 altura de ojos · 1 angular hacia abajo · 2 ajustar · 3 listo/REC
  return (
    <div className="strap-diagram" aria-hidden="true" data-step={step}>
      <div className="strap-scene">
        <div className="strap-floor"></div>
        {/* figura */}
        <div className="strap-shoulders">
          <span className="strap-sun"></span>
        </div>
        <div className="strap-neck"></div>
        <div className="strap-head"></div>
        <div className="strap-eye"></div>
        <div className="strap-smile"></div>
        <div className="strap-ear"></div>
        {/* cinta */}
        <div className={"strap-band" + (step >= 2 ? " tight" : "")}></div>
        {/* teléfono + cono de visión (se mueven juntos) */}
        <div className={"strap-rig" + (step < 2 ? " wobble" : "")}>
          <div className={"strap-phone" + (step >= 1 ? " down" : "")}>
            <span className="strap-lens"></span>
            {step === 3 ? <span className="strap-rec"></span> : null}
          </div>
          <div className={"strap-cone" + (step >= 1 ? " down" : "")}></div>
        </div>
        {/* línea de ojos */}
        <div className={"strap-eyeline" + (step === 0 ? " on" : "")}>
          <i>altura de los ojos</i>
        </div>
        {/* zona de manos */}
        <div className={"strap-hands" + (step >= 1 ? " seen" : "")}>
          <span className="strap-hand h1"></span>
          <span className="strap-hand h2"></span>
          <span className="strap-hands-label">{step >= 1 ? "✓ manos a la vista" : "manos"}</span>
        </div>
        {/* anotación del paso */}
        <div className={"strap-chip s" + step} key={step}>{STRAP_CHIPS[step]}</div>
      </div>
    </div>
  );
}

function StrapWalkthrough() {
  const steps = window.GUIDE.strapSteps;
  const [step, setStep] = useState(0);
  return (
    <div className="card strap-card">
      <StrapDiagram step={step} />
      <div className="strap-side">
        <div className="strap-steps">
          {steps.map((s, i) => (
            <button
              key={i}
              className={"strap-step" + (i === step ? " active" : "") + (i < step ? " done" : "")}
              onClick={() => setStep(i)}
            >
              <span className="strap-num">{i + 1}</span>
              <span className="strap-step-body">
                <strong>{s.title}</strong>
                {i === step ? <em>{s.desc}</em> : null}
              </span>
            </button>
          ))}
        </div>
        <div className="strap-nav">
          <button className="btn ghost" disabled={step === 0} onClick={() => setStep(step - 1)}>Anterior</button>
          <button className="btn solid" disabled={step === steps.length - 1} onClick={() => setStep(step + 1)}>Siguiente</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Verificador de teléfono ---------- */
function PhoneChecker() {
  const phones = window.GUIDE.phones;
  const [brand, setBrand] = useState(null);
  const [model, setModel] = useState(null);
  const b = brand ? phones[brand] : null;
  const verdict =
    model == null ? null : model.startsWith("ok:") ? true : false;
  return (
    <div className="card checker-card">
      <div className="checker-row">
        <label className="field-label">Marca</label>
        <div className="chip-row">
          {Object.keys(phones).map((k) => (
            <button
              key={k}
              className={"chip" + (brand === k ? " on" : "")}
              onClick={() => { setBrand(k); setModel(k === "other" ? "bad:other" : null); }}
            >
              {phones[k].label}
            </button>
          ))}
        </div>
      </div>
      {b && brand !== "other" ? (
        <div className="checker-row">
          <label className="field-label">Modelo</label>
          <div className="chip-row">
            {b.ok.map((m) => (
              <button key={m} className={"chip small" + (model === "ok:" + m ? " on" : "")} onClick={() => setModel("ok:" + m)}>{m}</button>
            ))}
            {b.bad.map((m) => (
              <button key={m} className={"chip small" + (model === "bad:" + m ? " on" : "")} onClick={() => setModel("bad:" + m)}>{m}</button>
            ))}
          </div>
        </div>
      ) : null}
      {verdict === true ? (
        <div className="verdict ok" data-comment-anchor="checker-verdict">
          <span className="verdict-dot"></span>
          <div><strong>¡Compatible!</strong> Tu material puede ser aceptado. Recuerda ingresar el código <code>3JQTT5F4</code> en la app.</div>
        </div>
      ) : verdict === false ? (
        <div className="verdict bad">
          <span className="verdict-dot"></span>
          <div><strong>No compatible.</strong> {brand === "other" ? "Solo se aceptan iPhone, Google Pixel y Samsung Galaxy S de la lista." : "Este modelo no producirá material aceptado."} Si tienes dudas, pregúntale a EGO.</div>
        </div>
      ) : (
        <p className="checker-hint">Elige tu marca y modelo para saber si tu material será aceptado.</p>
      )}
    </div>
  );
}

/* ---------- Lista previa a la sesión ---------- */
function PreflightChecklist() {
  const items = window.GUIDE.checklist;
  const KEY = "ego-checklist-v1";
  const [done, setDone] = useState(() => {
    try { return JSON.parse(localStorage.getItem(KEY)) || []; } catch (e) { return []; }
  });
  useEffect(() => { localStorage.setItem(KEY, JSON.stringify(done)); }, [done]);
  const toggle = (i) =>
    setDone(done.includes(i) ? done.filter((x) => x !== i) : [...done, i]);
  const pct = Math.round((done.length / items.length) * 100);
  return (
    <div className="card checklist-card">
      <div className="checklist-progress">
        <div className="progress-track"><div className="progress-fill" style={{ width: pct + "%" }}></div></div>
        <span className="progress-label">{done.length}/{items.length}</span>
      </div>
      <ul className="checklist">
        {items.map((item, i) => (
          <li key={i}>
            <button className={"check-item" + (done.includes(i) ? " checked" : "")} onClick={() => toggle(i)}>
              <span className="check-box">{done.includes(i) ? "✓" : ""}</span>
              <span>{item}</span>
            </button>
          </li>
        ))}
      </ul>
      {pct === 100 ? (
        <div className="verdict ok"><span className="verdict-dot"></span><div><strong>Todo listo.</strong> Dos minutos de revisión protegen toda tu sesión. ¡A grabar!</div></div>
      ) : (
        <div className="checklist-foot">
          <span>Repasa esta lista antes de <em>cada</em> sesión — el material rechazado no se paga.</span>
          <button className="btn ghost tiny" onClick={() => setDone([])}>Reiniciar</button>
        </div>
      )}
    </div>
  );
}

/* ---------- Mini quiz ---------- */
function MiniQuiz() {
  const qs = window.GUIDE.quiz;
  const [i, setI] = useState(0);
  const [answer, setAnswer] = useState(null); // true/false elegido
  const [score, setScore] = useState(0);
  const [finished, setFinished] = useState(false);
  const q = qs[i];
  const pick = (val) => {
    if (answer !== null) return;
    setAnswer(val);
    if (val === q.ok) setScore(score + 1);
  };
  const next = () => {
    if (i + 1 >= qs.length) { setFinished(true); return; }
    setI(i + 1); setAnswer(null);
  };
  const restart = () => { setI(0); setAnswer(null); setScore(0); setFinished(false); };
  if (finished) {
    return (
      <div className="card quiz-card">
        <div className="quiz-result">
          <div className="quiz-score">{score}<span>/{qs.length}</span></div>
          <p>{score === qs.length
            ? "Perfecto. Ya piensas como un revisor — tu material va por buen camino."
            : score >= qs.length - 2
            ? "¡Muy bien! Repasa las que fallaste y estarás listo."
            : "Buen intento. Vuelve a leer \u201cSí y No\u201d y \u201cQué se rechaza\u201d, e inténtalo de nuevo."}</p>
          <button className="btn solid" onClick={restart}>Repetir el quiz</button>
        </div>
      </div>
    );
  }
  return (
    <div className="card quiz-card">
      <div className="quiz-meta">Escenario {i + 1} de {qs.length}</div>
      <p className="quiz-q">{q.q}</p>
      <div className="quiz-actions">
        <button className={"btn quiz-btn ok" + (answer !== null && q.ok ? " reveal" : "") + (answer === true ? " picked" : "")} onClick={() => pick(true)} disabled={answer !== null}>Se acepta</button>
        <button className={"btn quiz-btn bad" + (answer !== null && !q.ok ? " reveal" : "") + (answer === false ? " picked" : "")} onClick={() => pick(false)} disabled={answer !== null}>Se rechaza</button>
      </div>
      {answer !== null ? (
        <div className={"verdict " + (answer === q.ok ? "ok" : "bad")}>
          <span className="verdict-dot"></span>
          <div>
            <strong>{answer === q.ok ? "¡Correcto!" : "No exactamente."}</strong> {q.why}
            <div className="quiz-next"><button className="btn solid tiny" onClick={next}>{i + 1 >= qs.length ? "Ver resultado" : "Siguiente"}</button></div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

/* ---------- FAQ ---------- */
function FaqList() {
  const [open, setOpen] = useState(0);
  return (
    <div className="faq-list">
      {window.GUIDE.faqs.map((f, i) => (
        <div className={"faq-item" + (open === i ? " open" : "")} key={i}>
          <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
            <span>{f.q}</span>
            <span className="faq-caret">{open === i ? "−" : "+"}</span>
          </button>
          {open === i ? <p className="faq-a">{f.a}</p> : null}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { StrapWalkthrough, PhoneChecker, PreflightChecklist, MiniQuiz, FaqList });
