// Kiosco CLS 2026 — Autoevaluación de Ruta Empresarial
// Vertical kiosk (1080×1920) — scales to fit viewport, letterboxed.

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

/* ----------------------------- DATA ----------------------------- */

const QUESTIONS = [
  {
    id: 1,
    text: "¿Cuál es el mayor reto de tu negocio hoy?",
    options: [
      { letter: "A", text: "Conseguir permisos, cumplir requisitos o formalizarme.", route: "nacimiento" },
      { letter: "B", text: "Identificar incentivos u otras fuentes de capital o financiamiento.", route: "desarrollo" },
      { letter: "C", text: "Aumentar la base de clientes, crecer o vender más.", route: "crecimiento" },
    ],
  },
  {
    id: 2,
    text: "¿Qué área necesitas fortalecer más?",
    options: [
      { letter: "A", text: "Recursos humanos, nómina o cumplimiento.", route: "nacimiento" },
      { letter: "B", text: "Tecnología, inteligencia artificial o servicio al cliente.", route: "crecimiento" },
      { letter: "C", text: "Organización o estructura del negocio.", route: "desarrollo" },
    ],
  },
  {
    id: 3,
    text: "¿Tu negocio o empresa está formalmente organizado?",
    options: [
      { letter: "A", text: "Apenas estoy comenzando.", route: "nacimiento" },
      { letter: "B", text: "Sí, pero necesito orientación adicional.", route: "desarrollo" },
      { letter: "C", text: "Sí, y quiero crecer o expandirme.", route: "crecimiento" },
    ],
  },
  {
    id: 4,
    text: "¿Qué tema te interesa más hoy?",
    options: [
      { letter: "A", text: "Permisos y documentos empresariales para crecer.", route: "nacimiento" },
      { letter: "B", text: "Reforma contributiva e incentivos.", route: "desarrollo" },
      { letter: "C", text: "Inteligencia artificial y crecimiento.", route: "crecimiento" },
    ],
  },
  {
    id: 5,
    text: "¿Qué buscas lograr hoy en el evento?",
    options: [
      { letter: "A", text: "Orientarme sobre programas y apoyo.", route: "desarrollo" },
      { letter: "B", text: "Aprender herramientas prácticas.", route: "crecimiento" },
      { letter: "C", text: "Hacer conexiones y descubrir oportunidades.", route: "crecimiento" },
    ],
  },
];

const ROUTES = {
  nacimiento: {
    key: "nacimiento",
    name: "Nacimiento",
    number: "01",
    accent: "var(--eslabon-lime)",
    accentDeep: "var(--eslabon-green)",
    message: "Estás dando los primeros pasos. Esta ruta te dará las bases para arrancar con fuerza.",
    icon: "seed",
    participa: [
      { type: "Conferencia", title: "Sin fronteras: cómo conquistar mercados globales desde P.R." },
      { type: "Taller", title: "Cumplimiento Laboral: expedientes, nómina y manejo de recursos humanos." },
      { type: "Taller", title: "Permisos y documentos para crecer: RUL, RUP y SAM." },
      { type: "Taller", title: "De la idea al modelo de ingresos." },
    ],
    visita: {
      exhibidor: "Conexión Laboral Sureste",
      mesas: [
        "INSEC",
        "Pathstone",
        "Departamento de Desarrollo Económico y Comercio de PR",
        "Municipios participantes",
      ],
    },
  },
  desarrollo: {
    key: "desarrollo",
    name: "Desarrollo",
    number: "02",
    accent: "var(--brand-cyan-500)",
    accentDeep: "var(--brand-cyan-700)",
    message: "Tu negocio está en marcha. Esta ruta te ayudará a fortalecer estructura y proyección.",
    icon: "grow",
    participa: [
      { type: "Conferencia", title: "Sin fronteras: cómo conquistar mercados globales desde P.R." },
      { type: "Conversatorio", title: "Visión 360°: el futuro del desarrollo económico desde el Sureste." },
      { type: "Taller", title: "Crecimiento Digital: IA aplicada a ventas y servicio al cliente." },
      { type: "Taller", title: "Permisos y documentos para crecer: RUP, RUL y SAM." },
      { type: "Taller", title: "De la idea al modelo de ingresos." },
    ],
    visita: {
      exhibidor: "Conexión Laboral Sureste",
      mesas: [
        "INSEC",
        "Pathstone",
        "Banco de Desarrollo Económico de Puerto Rico",
        "Departamento de Desarrollo Económico y Comercio de PR",
        "Municipios participantes",
      ],
    },
  },
  crecimiento: {
    key: "crecimiento",
    name: "Crecimiento",
    number: "03",
    accent: "var(--cta)",
    accentDeep: "var(--cta-deep)",
    message: "Estás listo para escalar. Esta ruta te conecta con capital, IA y oportunidades de expansión.",
    icon: "scale",
    participa: [
      { type: "Conferencia", title: "Sin fronteras: cómo conquistar mercados globales desde P.R." },
      { type: "Conversatorio", title: "Visión 360°: el futuro del desarrollo económico desde el Sureste." },
      { type: "Panel / Taller", title: "Reforma de Permisos · ó · Crecimiento Digital: IA aplicada a ventas." },
      { type: "Panel", title: "¿Dónde están los chavos?" },
    ],
    visita: {
      exhibidor: "Conexión Laboral Sureste",
      mesas: [
        "Banco de Desarrollo Económico de Puerto Rico",
        "Departamento de Desarrollo Económico y Comercio de PR",
        "Municipios participantes",
      ],
    },
  },
};

/* --------------------------- ICONS (inline SVG) --------------------------- */
const RouteIcon = ({ kind, color }) => {
  const stroke = color || "currentColor";
  if (kind === "seed") {
    return (
      <svg viewBox="0 0 64 64" width="100%" height="100%" fill="none" stroke={stroke} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
        <path d="M32 56V30" />
        <path d="M32 30c0-10 8-18 18-18-1 11-8 18-18 18Z" />
        <path d="M32 38c0-7-6-12-13-12 1 8 6 12 13 12Z" />
        <path d="M18 56h28" />
      </svg>
    );
  }
  if (kind === "grow") {
    return (
      <svg viewBox="0 0 64 64" width="100%" height="100%" fill="none" stroke={stroke} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
        <path d="M10 54h44" />
        <rect x="14" y="38" width="10" height="16" rx="1.5" />
        <rect x="27" y="28" width="10" height="26" rx="1.5" />
        <rect x="40" y="18" width="10" height="36" rx="1.5" />
        <path d="M14 14l10-4 10 6 10-6" />
      </svg>
    );
  }
  // scale / expansion
  return (
    <svg viewBox="0 0 64 64" width="100%" height="100%" fill="none" stroke={stroke} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="32" cy="32" r="6" />
      <path d="M32 12V4M32 60v-8M12 32H4M60 32h-8M18 18l-6-6M52 52l-6-6M18 46l-6 6M52 12l-6 6" />
      <circle cx="32" cy="32" r="20" strokeDasharray="2 6" />
    </svg>
  );
};

const ArrowRight = (props) => (
  <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <path d="M5 12h14M13 5l7 7-7 7" />
  </svg>
);

const ArrowLeft = (props) => (
  <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <path d="M19 12H5M11 5l-7 7 7 7" />
  </svg>
);

const RefreshIcon = (props) => (
  <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <path d="M3 12a9 9 0 0 1 15.5-6.3L21 8" />
    <path d="M21 3v5h-5" />
    <path d="M21 12a9 9 0 0 1-15.5 6.3L3 16" />
    <path d="M3 21v-5h5" />
  </svg>
);

const ClockIcon = (props) => (
  <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <circle cx="12" cy="12" r="9" />
    <path d="M12 7v5l3 2" />
  </svg>
);

const SparkIcon = (props) => (
  <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M6 18l2.5-2.5M15.5 8.5L18 6" />
  </svg>
);

/* --------------------------- LAYOUT FRAME --------------------------- */

function KioskHeader() {
  return (
    <header className="k-header">
      <div className="k-brand">
        <img src="assets/eslabon-medallion.png" alt="" className="k-medallion" />
        <div className="k-brand-text">
          <div className="k-brand-eyebrow">UPGRADE EMPRESARIAL SUMMIT</div>
          <div className="k-brand-event">CLS · 2026 — Puerto Rico</div>
        </div>
      </div>
      <div className="k-header-right">
        <div className="k-header-pill">Autoevaluación</div>
      </div>
    </header>
  );
}

function KioskFooter({ children }) {
  return (
    <footer className="k-footer">
      <div className="k-footer-left">
        <span className="k-footer-mark">Powered by Conexión Laboral · DDEC</span>
      </div>
      <div className="k-footer-right">{children}</div>
    </footer>
  );
}

/* --------------------------- SCREENS --------------------------- */

function Welcome({ onStart }) {
  return (
    <section className="screen screen-welcome" data-screen-label="01 Welcome">
      <div className="welcome-inner">
        <img
          src="assets/conexion-laboral-sureste.png"
          alt="Conexión Laboral · Área Local Sureste"
          className="welcome-logo"
        />

        <div className="welcome-eyebrow">
          <span className="dot" /> AUTOEVALUACIÓN EMPRESARIAL
        </div>

        <h1 className="welcome-title">
          Explora oportunidades.
          <br />
          <span className="welcome-title-accent">Diseña tu ruta.</span>
        </h1>

        <p className="welcome-sub">¿Qué ruta debes hacer hoy?</p>

        <p className="welcome-desc">
          Responde 5 preguntas rápidas y te recomendaremos la agenda perfecta
          —conferencias, talleres y exhibidores— para llevar tu negocio al
          próximo nivel en el Upgrade Empresarial Summit.
        </p>

        <div className="welcome-meta">
          <div className="meta-chip">
            <SparkIcon /> 5 preguntas
          </div>
          <div className="meta-chip">
            <ClockIcon /> 1 minuto
          </div>
          <div className="meta-chip">
            <RouteIcon kind="grow" /> 3 rutas
          </div>
        </div>

        <button className="btn-primary btn-huge" onClick={onStart}>
          <span>¡Comencemos!</span>
          <ArrowRight />
        </button>
      </div>

      <div className="welcome-routes">
        <span className="welcome-routes-label">Rutas disponibles</span>
        <div className="route-pips">
          <div className="route-pip" style={{ "--c": "var(--eslabon-lime)" }}>
            <span className="pip-num">01</span>
            <span className="pip-name">Nacimiento</span>
          </div>
          <div className="route-pip" style={{ "--c": "var(--brand-cyan-500)" }}>
            <span className="pip-num">02</span>
            <span className="pip-name">Desarrollo</span>
          </div>
          <div className="route-pip" style={{ "--c": "var(--cta)" }}>
            <span className="pip-num">03</span>
            <span className="pip-name">Crecimiento</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function Question({ index, selected, onSelect, onBack, onNext }) {
  const q = QUESTIONS[index];
  const total = QUESTIONS.length;
  const pct = ((index + (selected != null ? 1 : 0)) / total) * 100;

  return (
    <section className="screen screen-question" data-screen-label={`Q${index + 1}`}>
      <div className="q-progress">
        <div className="q-progress-head">
          <span className="q-progress-label">
            Pregunta <strong>{index + 1}</strong> de {total}
          </span>
          <span className="q-progress-pct">{Math.round(((index + 1) / total) * 100)}%</span>
        </div>
        <div className="q-progress-bar">
          <div className="q-progress-fill" style={{ width: `${((index + 1) / total) * 100}%` }} />
        </div>
        <div className="q-progress-dots">
          {QUESTIONS.map((_, i) => (
            <span
              key={i}
              className={`dot ${i < index ? "done" : i === index ? "active" : ""}`}
            />
          ))}
        </div>
      </div>

      <div className="q-body">
        <div className="q-eyebrow">PREGUNTA {String(index + 1).padStart(2, "0")}</div>
        <h2 className="q-title">{q.text}</h2>

        <div className="q-options">
          {q.options.map((opt, i) => {
            const isSel = selected === i;
            return (
              <button
                key={i}
                className={`q-option ${isSel ? "is-selected" : ""}`}
                onClick={() => onSelect(i)}
              >
                <span className="q-option-letter">{opt.letter}</span>
                <span className="q-option-text">{opt.text}</span>
                <span className="q-option-check" aria-hidden>
                  <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M5 12l5 5L20 7" />
                  </svg>
                </span>
              </button>
            );
          })}
        </div>
      </div>

      <div className="q-actions">
        <button
          className="btn-primary"
          onClick={onNext}
          disabled={selected == null}
        >
          {index === total - 1 ? "Ver mi ruta" : "Continuar"} <ArrowRight />
        </button>
      </div>
    </section>
  );
}

function Result({ routeKey, onRestart }) {
  const r = ROUTES[routeKey];
  return (
    <section className="screen screen-result" data-screen-label={`Result-${r.name}`}>
      <div className="result-banner" style={{ "--accent": r.accent, "--accent-deep": r.accentDeep }}>
        <div className="result-banner-inner">
          <div className="result-eyebrow">TU RUTA RECOMENDADA</div>
          <div className="result-hero">
            <div className="result-route-icon">
              <RouteIcon kind={r.icon} color="currentColor" />
            </div>
            <div className="result-hero-text">
              <div className="result-route-number">RUTA {r.number}</div>
              <h1 className="result-route-name">{r.name.toUpperCase()}</h1>
            </div>
          </div>
          <p className="result-message">{r.message}</p>
        </div>
      </div>

      <div className="result-body">
        <div className="result-col">
          <div className="result-col-head">
            <span className="result-col-num">01</span>
            <div>
              <div className="result-col-eyebrow">AGENDA</div>
              <h3 className="result-col-title">Participa de</h3>
            </div>
          </div>
          <ul className="result-list">
            {r.participa.map((p, i) => (
              <li key={i} className="result-item">
                <span className="result-item-tag">
                  {p.type}
                </span>
                <span className="result-item-text">{p.title}</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="result-col">
          <div className="result-col-head">
            <span className="result-col-num">02</span>
            <div>
              <div className="result-col-eyebrow">EXHIBIDORES</div>
              <h3 className="result-col-title">Visita</h3>
            </div>
          </div>

          <div className="result-exhibitor">
            <div className="result-exhibitor-label">Exhibidor destacado</div>
            <div className="result-exhibitor-name">{r.visita.exhibidor}</div>
          </div>

          <div className="result-mesas-label">Mesas de:</div>
          <ul className="result-mesas">
            {r.visita.mesas.map((m, i) => (
              <li key={i} className="result-mesa">
                <span className="result-mesa-dot" style={{ background: r.accent }} />
                {m}
              </li>
            ))}
          </ul>
        </div>
      </div>

      <div className="result-cta">
        <p className="result-cta-sub">
          Toma una foto a esta pantalla para llevar tu agenda contigo.
        </p>
        <button className="btn-primary" onClick={onRestart}>
          <RefreshIcon /> <span>Finalizar</span>
        </button>
      </div>
    </section>
  );
}

/* --------------------------- APP --------------------------- */

function App() {
  const [screen, setScreen] = useState("lobby"); // lobby | question | result
  const [qIndex, setQIndex] = useState(0);
  const [answers, setAnswers] = useState(Array(QUESTIONS.length).fill(null));
  const [scores, setScores] = useState({ nacimiento: 0, desarrollo: 0, crecimiento: 0 });
  const [transitionKey, setTransitionKey] = useState("lobby-0");

  const inactivityTimer = useRef(null);

  const reset = useCallback(() => {
    setScreen("lobby");
    setQIndex(0);
    setAnswers(Array(QUESTIONS.length).fill(null));
    setScores({ nacimiento: 0, desarrollo: 0, crecimiento: 0 });
    setTransitionKey("lobby-" + Date.now());
  }, []);

  // Inactivity reset (60s)
  useEffect(() => {
    const arm = () => {
      if (inactivityTimer.current) clearTimeout(inactivityTimer.current);
      inactivityTimer.current = setTimeout(() => {
        if (screen !== "lobby") reset();
      }, 60000);
    };
    arm();
    const events = ["pointerdown", "keydown", "touchstart"];
    events.forEach((e) => window.addEventListener(e, arm));
    return () => {
      events.forEach((e) => window.removeEventListener(e, arm));
      if (inactivityTimer.current) clearTimeout(inactivityTimer.current);
    };
  }, [screen, reset]);

  const computeWinner = (sc) => {
    const max = Math.max(sc.nacimiento, sc.desarrollo, sc.crecimiento);
    // Tiebreaker: always Crecimiento
    if (sc.crecimiento === max) return "crecimiento";
    if (sc.desarrollo === max) return "desarrollo";
    return "nacimiento";
  };

  const handleStart = () => {
    setScreen("question");
    setQIndex(0);
    setTransitionKey("q-0-" + Date.now());
  };

  const handleSelect = (optIndex) => {
    const next = [...answers];
    next[qIndex] = optIndex;
    setAnswers(next);
  };

  const handleNext = () => {
    const opt = QUESTIONS[qIndex].options[answers[qIndex]];
    const newScores = { ...scores, [opt.route]: scores[opt.route] + 1 };
    setScores(newScores);

    if (qIndex < QUESTIONS.length - 1) {
      setQIndex(qIndex + 1);
      setTransitionKey("q-" + (qIndex + 1) + "-" + Date.now());
    } else {
      setScreen("result");
      setTransitionKey("result-" + Date.now());
    }
  };

  const handleBack = () => {
    if (qIndex === 0) return;
    // Roll back the score that was added when leaving the previous question
    const prevAns = answers[qIndex - 1];
    if (prevAns != null) {
      const prevOpt = QUESTIONS[qIndex - 1].options[prevAns];
      setScores((s) => ({ ...s, [prevOpt.route]: Math.max(0, s[prevOpt.route] - 1) }));
    }
    setQIndex(qIndex - 1);
    setTransitionKey("q-back-" + (qIndex - 1) + "-" + Date.now());
  };

  const winner = useMemo(() => computeWinner(scores), [scores]);

  return (
    <div className="kiosk-root">
      <div className="kiosk-bg" />
      <div className="kiosk-frame" data-accent="magenta">
        <KioskHeader />

        <main className="kiosk-main" key={transitionKey}>
          {screen === "lobby" && <Welcome onStart={handleStart} />}
          {screen === "question" && (
            <Question
              index={qIndex}
              selected={answers[qIndex]}
              onSelect={handleSelect}
              onBack={handleBack}
              onNext={handleNext}
            />
          )}
          {screen === "result" && <Result routeKey={winner} onRestart={reset} />}
        </main>

        <KioskFooter>
          {screen !== "lobby" && (
            <button className="footer-restart" onClick={reset}>
              <RefreshIcon /> Reiniciar
            </button>
          )}
        </KioskFooter>
      </div>

    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
