/* global React, Icon, window */
// ============================================================================
// Chantier J · Wizard d'onboarding 5 minutes
// ----------------------------------------------------------------------------
// Modal full-screen multi-étapes auto-déclenché pour les nouvelles
// organisations (créées < 7 j, sans projet, wizard pas dismissed).
//
// 5 étapes :
//   1. Bienvenue + infos org (nom, pays, secteurs cibles)
//   2. Inviter 2-3 collègues (skip possible)
//   3. Choisir un template métier (Santé / Gouvernance / Agriculture /
//      Éducation / Vide) — pré-charge 1 programme + 1 projet + 8 indicateurs
//   4. Confirmer le plan (Free par défaut, lien vers /pricing)
//   5. "Vous êtes prêt !" + 3 actions recommandées
//
// L'utilisateur peut :
//   - Avancer/Reculer/Skip une étape
//   - Fermer le wizard (marqué dismissed=true, ne s'ouvre plus auto)
//   - Reprendre depuis la sidebar via le chip "Démarrage X/5"
// ============================================================================

(function () {
  const { useState, useEffect, useMemo } = React;

  function OnboardingWizard({ lang, orgId, orgName, onClose, onComplete }) {
    const { data: state, refresh } = window.melr.useOnboardingState(orgId);
    const { data: templates } = window.melr.useOnboardingTemplates();

    // Step courant : tire de la BDD (state.current_step), default 1
    const [step, setStep] = useState((state && state.current_step) || 1);
    useEffect(() => { if (state && state.current_step && state.current_step !== step) setStep(state.current_step); }, [state && state.current_step]);

    // États locaux des 5 étapes
    const [orgInfo, setOrgInfo] = useState({ countries: "", description: "" });
    const [invites, setInvites] = useState(["", "", ""]);
    const [chosenTemplate, setChosenTemplate] = useState(null);
    const [applying, setApplying] = useState(false);
    const [applyError, setApplyError] = useState(null);
    const [applyResult, setApplyResult] = useState(null);

    const advance = async (target) => {
      const next = target || step + 1;
      try { await window.melr.onboardingCrud.advance(orgId, step); } catch (e) { console.warn(e); }
      setStep(next);
      await refresh();
    };
    const skip = async () => {
      try { await window.melr.onboardingCrud.skip(orgId, step); } catch (e) { console.warn(e); }
      setStep(step + 1);
      await refresh();
    };
    const dismiss = async () => {
      try { await window.melr.onboardingCrud.dismiss(orgId); } catch (e) { console.warn(e); }
      onClose && onClose();
    };
    const finish = async () => {
      try { await window.melr.onboardingCrud.complete(orgId); } catch (e) { console.warn(e); }
      onComplete && onComplete();
    };

    const onApplyTemplate = async () => {
      if (!chosenTemplate) { setApplyError(window.L("Choisissez un template", "Pick a template", "Elija una plantilla")); return; }
      setApplying(true); setApplyError(null);
      try {
        const r = await window.melr.applyOnboardingTemplate(orgId, chosenTemplate);
        setApplyResult(r && r[0]);
        await advance(4);
      } catch (e) {
        setApplyError(e.message || String(e));
      } finally {
        setApplying(false);
      }
    };

    // ── Sub-renderer par étape ─────────────────────────────────────────
    const renderStep = () => {
      switch (step) {
        case 1: return <StepWelcome lang={lang} orgName={orgName} orgInfo={orgInfo} setOrgInfo={setOrgInfo} />;
        case 2: return <StepInvites lang={lang} invites={invites} setInvites={setInvites} />;
        case 3: return <StepTemplate lang={lang} templates={templates} chosen={chosenTemplate} setChosen={setChosenTemplate} applying={applying} error={applyError} result={applyResult} />;
        case 4: return <StepPlan lang={lang} />;
        case 5: return <StepDone lang={lang} appliedTemplate={chosenTemplate} templates={templates} />;
        default: return null;
      }
    };

    const stepLabels = [
      window.L("Bienvenue", "Welcome", "Bienvenida"),
      window.L("Équipe", "Team", "Equipo"),
      window.L("Démarrage", "Quick-start", "Inicio rápido"),
      window.L("Plan", "Plan", "Plan"),
      window.L("Prêt !", "Ready!", "¡Listo!"),
    ];

    return (
      <div style={{
        position: "fixed", inset: 0, zIndex: 99990,
        background: "rgba(15, 23, 42, 0.65)",
        backdropFilter: "blur(4px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 20,
      }}>
        <div style={{
          background: "white", borderRadius: 16,
          width: "100%", maxWidth: 760, maxHeight: "90vh",
          overflow: "hidden", display: "flex", flexDirection: "column",
          boxShadow: "0 20px 80px rgba(0,0,0,0.4)",
        }}>
          {/* Header avec progress bar */}
          <div style={{ padding: "20px 28px 0", borderBottom: "1px solid #e2e8f0" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
              <div>
                <div style={{ fontSize: 11, color: "#64748b", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 700 }}>
                  {window.L("DÉMARRAGE MELR", "MELR ONBOARDING", "INTRODUCCIÓN A MELR")}
                </div>
                <div style={{ fontSize: 22, fontWeight: 800, color: "#0f172a", marginTop: 2 }}>
                  {stepLabels[step - 1]}
                </div>
              </div>
              <button onClick={dismiss}
                title={window.L("Reporter pour plus tard", "Skip for later", "Posponer para más tarde")}
                style={{ background: "transparent", border: "none", color: "#94a3b8", cursor: "pointer", fontSize: 14 }}>
                {window.L("Reporter ×", "Skip ×", "Posponer ×")}
              </button>
            </div>
            {/* Progress dots */}
            <div style={{ display: "flex", alignItems: "center", gap: 6, paddingBottom: 18 }}>
              {[1, 2, 3, 4, 5].map((i) => (
                <div key={i} style={{
                  flex: 1, height: 4, borderRadius: 2,
                  background: i < step ? "#0f766e" : i === step ? "#0f766e" : "#e2e8f0",
                  opacity: i < step ? 0.7 : 1,
                  transition: "background 200ms",
                }} />
              ))}
              <span style={{ marginLeft: 8, fontSize: 11, color: "#64748b", fontWeight: 600 }}>
                {step} / 5
              </span>
            </div>
          </div>

          {/* Step body — scrollable */}
          <div style={{ flex: 1, overflow: "auto", padding: "24px 28px" }}>
            {renderStep()}
          </div>

          {/* Footer actions */}
          <div style={{ padding: "16px 28px", borderTop: "1px solid #e2e8f0", display: "flex", justifyContent: "space-between", gap: 10 }}>
            <div>
              {step > 1 && step < 5 && (
                <button onClick={() => setStep(step - 1)}
                  style={{ padding: "10px 16px", borderRadius: 8, border: "1px solid #cbd5e1", background: "white", color: "#0f172a", cursor: "pointer", fontWeight: 600, fontSize: 13 }}>
                  ← {window.L("Retour", "Back", "Atrás")}
                </button>
              )}
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              {step > 1 && step < 4 && (
                <button onClick={skip}
                  style={{ padding: "10px 16px", borderRadius: 8, border: "1px solid transparent", background: "transparent", color: "#64748b", cursor: "pointer", fontWeight: 500, fontSize: 13 }}>
                  {window.L("Passer cette étape", "Skip this step", "Omitir este paso")}
                </button>
              )}
              {step === 3 && (
                <button onClick={onApplyTemplate} disabled={!chosenTemplate || applying}
                  style={{ padding: "10px 20px", borderRadius: 8, border: "none", background: chosenTemplate ? "#0f766e" : "#94a3b8", color: "white", cursor: chosenTemplate ? "pointer" : "not-allowed", fontWeight: 700, fontSize: 13 }}>
                  {applying ? (window.L("Création…", "Creating…", "Creando…")) : (window.L("Appliquer →", "Apply →", "Aplicar →"))}
                </button>
              )}
              {step !== 3 && step < 5 && (
                <button onClick={() => advance()}
                  style={{ padding: "10px 20px", borderRadius: 8, border: "none", background: "#0f766e", color: "white", cursor: "pointer", fontWeight: 700, fontSize: 13 }}>
                  {window.L("Continuer", "Continue", "Continuar")} →
                </button>
              )}
              {step === 5 && (
                <button onClick={finish}
                  style={{ padding: "10px 22px", borderRadius: 8, border: "none", background: "#0f766e", color: "white", cursor: "pointer", fontWeight: 700, fontSize: 14 }}>
                  {window.L("Terminer 🎉", "Finish 🎉", "Finalizar 🎉")}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── Étape 1 : Bienvenue + infos org ───────────────────────────────────
  function StepWelcome({ lang, orgName, orgInfo, setOrgInfo }) {
    return (
      <div>
        <div style={{ fontSize: 48, marginBottom: 14, textAlign: "center" }}>👋</div>
        <h2 style={{ fontSize: 22, fontWeight: 700, textAlign: "center", margin: "0 0 8px", color: "#0f172a" }}>
          {window.L(`Bienvenue dans MELR, ${orgName || "votre organisation"} !`, `Welcome to MELR, ${orgName || "your organization"}!`, `¡Bienvenido a MELR, ${orgName || "su organización"}!`)}
        </h2>
        <p style={{ fontSize: 14, color: "#475569", textAlign: "center", margin: "0 auto 22px", maxWidth: 480, lineHeight: 1.55 }}>
          {window.L("En 5 minutes, on vous installe votre première organisation MELR : équipe, premier projet, indicateurs. C'est parti.", "In 5 minutes, we'll set up your first MELR organization: team, first project, indicators. Let's go.", "En 5 minutos, le configuramos su primera organización MELR: equipo, primer proyecto, indicadores. Adelante.")}
        </p>
        <div style={{ background: "#f1f5f9", borderRadius: 10, padding: "18px 20px", marginTop: 6 }}>
          <label style={{ display: "block", fontSize: 12, fontWeight: 700, color: "#475569", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 6 }}>
            {window.L("Pays d'intervention (optionnel)", "Countries (optional)", "Países de intervención (opcional)")}
          </label>
          <input value={orgInfo.countries} onChange={(e) => setOrgInfo({ ...orgInfo, countries: e.target.value })}
            placeholder={window.L("ex. Sénégal, Mali, Côte d'Ivoire", "e.g. Senegal, Mali, Côte d'Ivoire", "p. ej. Senegal, Mali, Côte d'Ivoire")}
            style={{ width: "100%", padding: "10px 12px", borderRadius: 6, border: "1px solid #cbd5e1", fontSize: 13, boxSizing: "border-box" }} />
          <label style={{ display: "block", fontSize: 12, fontWeight: 700, color: "#475569", textTransform: "uppercase", letterSpacing: "0.04em", marginTop: 14, marginBottom: 6 }}>
            {window.L("Décrivez votre mission en 1 phrase (optionnel)", "Describe your mission in 1 sentence (optional)", "Describa su misión en 1 frase (opcional)")}
          </label>
          <textarea value={orgInfo.description} onChange={(e) => setOrgInfo({ ...orgInfo, description: e.target.value })}
            placeholder={window.L("ex. Améliorer l'accès aux soins en zone rurale", "e.g. Improve healthcare access in rural areas", "p. ej. Mejorar el acceso a la atención sanitaria en zonas rurales")}
            rows={2}
            style={{ width: "100%", padding: "10px 12px", borderRadius: 6, border: "1px solid #cbd5e1", fontSize: 13, fontFamily: "inherit", resize: "vertical", boxSizing: "border-box" }} />
          <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 10 }}>
            {window.L("Ces informations sont optionnelles — vous pouvez les compléter plus tard depuis Paramètres.", "These fields are optional — you can fill them later from Settings.", "Esta información es opcional — puede completarla más tarde desde Ajustes.")}
          </div>
        </div>
      </div>
    );
  }

  // ── Étape 2 : Inviter l'équipe ────────────────────────────────────────
  function StepInvites({ lang, invites, setInvites }) {
    return (
      <div>
        <div style={{ fontSize: 48, marginBottom: 14, textAlign: "center" }}>👥</div>
        <h2 style={{ fontSize: 22, fontWeight: 700, textAlign: "center", margin: "0 0 8px", color: "#0f172a" }}>
          {window.L("Invitez votre équipe", "Invite your team", "Invite a su equipo")}
        </h2>
        <p style={{ fontSize: 14, color: "#475569", textAlign: "center", margin: "0 auto 22px", maxWidth: 480 }}>
          {window.L("MELR est conçu pour le travail collaboratif. Invitez 2-3 collègues maintenant ou plus tard depuis « Organisation & rôles ».", "MELR is built for collaborative work. Invite 2-3 colleagues now or later from \"Organization & roles\".", "MELR está diseñado para el trabajo colaborativo. Invite a 2-3 colegas ahora o más tarde desde « Organización y roles ».")}
        </p>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {invites.map((email, i) => (
            <input key={i} type="email"
              value={email}
              onChange={(e) => { const a = invites.slice(); a[i] = e.target.value; setInvites(a); }}
              placeholder={(window.L("collègue ", "colleague ", "colega ")) + (i + 1) + "@org.com"}
              style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #cbd5e1", fontSize: 13 }} />
          ))}
        </div>
        <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 12, textAlign: "center" }}>
          {window.L("💡 Chaque invité recevra un email avec un lien personnel pour rejoindre votre organisation.", "💡 Each invitee will get an email with a personal link to join your organization.", "💡 Cada invitado recibirá un correo con un enlace personal para unirse a su organización.")}
        </div>
      </div>
    );
  }

  // ── Étape 3 : Template métier ─────────────────────────────────────────
  function StepTemplate({ lang, templates, chosen, setChosen, applying, error, result }) {
    if (!templates || templates.length === 0) {
      return <div style={{ padding: 40, textAlign: "center", color: "#94a3b8" }}>{window.L("Chargement des modèles…", "Loading templates…", "Cargando plantillas…")}</div>;
    }
    return (
      <div>
        <div style={{ fontSize: 48, marginBottom: 14, textAlign: "center" }}>🎯</div>
        <h2 style={{ fontSize: 22, fontWeight: 700, textAlign: "center", margin: "0 0 8px", color: "#0f172a" }}>
          {window.L("Démarrage rapide", "Quick-start", "Inicio rápido")}
        </h2>
        <p style={{ fontSize: 14, color: "#475569", textAlign: "center", margin: "0 auto 18px", maxWidth: 500 }}>
          {window.L("Choisissez un modèle métier — on vous pré-remplit un programme, un projet et 8 indicateurs catalogue. Vous gagnez 1-2 heures de configuration.", "Pick a domain template — we'll pre-fill a programme, a project, and 8 catalogue indicators. Saves 1-2 hours of setup.", "Elija una plantilla sectorial — le precargamos un programa, un proyecto y 8 indicadores de catálogo. Ahorra 1-2 horas de configuración.")}
        </p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 10 }}>
          {templates.map((tpl) => {
            const active = chosen === tpl.code;
            return (
              <button key={tpl.code} onClick={() => setChosen(tpl.code)}
                disabled={applying}
                style={{
                  padding: "16px 14px", borderRadius: 10,
                  border: "2px solid " + (active ? "#0f766e" : "#e2e8f0"),
                  background: active ? "#f0fdfa" : "white",
                  cursor: applying ? "wait" : "pointer",
                  textAlign: "left", transition: "all 120ms",
                  boxShadow: active ? "0 4px 12px rgba(15,118,110,0.15)" : "none",
                }}>
                <div style={{ fontSize: 30, marginBottom: 6 }}>{tpl.icon_emoji || "📋"}</div>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>
                  {(lang === "es" ? (tpl.name_es != null ? tpl.name_es : tpl.name_en) : lang === "fr" ? tpl.name_fr : tpl.name_en)}
                </div>
                <div style={{ fontSize: 11.5, color: "#64748b", lineHeight: 1.45 }}>
                  {(lang === "es" ? (tpl.description_es != null ? tpl.description_es : tpl.description_en) : lang === "fr" ? tpl.description_fr : tpl.description_en)}
                </div>
              </button>
            );
          })}
        </div>
        {error && (
          <div style={{ marginTop: 14, padding: "10px 14px", background: "#fee2e2", color: "#7f1d1d", borderRadius: 6, fontSize: 13 }}>
            ⚠ {error}
          </div>
        )}
        {result && (
          <div style={{ marginTop: 14, padding: "10px 14px", background: "#dcfce7", color: "#065f46", borderRadius: 6, fontSize: 13 }}>
            ✓ {window.L(`Programme + projet créés, ${result.indicator_count} indicateurs ajoutés au catalogue.`, `Programme + project created, ${result.indicator_count} indicators added to catalogue.`, `Programa + proyecto creados, ${result.indicator_count} indicadores añadidos al catálogo.`)}
          </div>
        )}
      </div>
    );
  }

  // ── Étape 4 : Plan ────────────────────────────────────────────────────
  function StepPlan({ lang }) {
    return (
      <div>
        <div style={{ fontSize: 48, marginBottom: 14, textAlign: "center" }}>💎</div>
        <h2 style={{ fontSize: 22, fontWeight: 700, textAlign: "center", margin: "0 0 8px", color: "#0f172a" }}>
          {window.L("Votre plan", "Your plan", "Su plan")}
        </h2>
        <p style={{ fontSize: 14, color: "#475569", textAlign: "center", margin: "0 auto 22px", maxWidth: 500 }}>
          {window.L("Vous démarrez sur le plan Gratuit — 2 projets, 3 utilisateurs, fonctionnalités de base. Suffisant pour valider MELR sur un cas d'usage.", "You're starting on the Free plan — 2 projects, 3 users, core features. Enough to validate MELR on a single use case.", "Empieza con el plan Gratuito — 2 proyectos, 3 usuarios, funciones básicas. Suficiente para validar MELR en un caso de uso.")}
        </p>
        <div style={{ background: "linear-gradient(135deg,#fef3c7,#fffbeb)", border: "2px solid #fcd34d", borderRadius: 12, padding: 24, textAlign: "center" }}>
          <div style={{ fontSize: 32, fontWeight: 800, color: "#92400e" }}>{window.L("Gratuit", "Free", "Gratuito")}</div>
          <div style={{ fontSize: 13, color: "#78350f", marginTop: 8 }}>
            {window.L("Sans engagement · pas de carte bancaire", "No commitment · no credit card", "Sin compromiso · sin tarjeta bancaria")}
          </div>
        </div>
        <div style={{ marginTop: 16, padding: 14, background: "#f1f5f9", borderRadius: 10, fontSize: 12.5, color: "#475569", textAlign: "center" }}>
          {window.L("Besoin de plus ? Consultez les plans Pro et Enterprise sur ", "Need more? Check Pro and Enterprise plans on ", "¿Necesita más? Consulte los planes Pro y Enterprise en ")}
          <a href="/MELR?pricing=1" target="_blank" rel="noopener noreferrer" style={{ color: "#0f766e", fontWeight: 700 }}>
            /pricing
          </a>
          {window.L(" (Ex-ante, DHIS2, MSC, exports bailleurs…)", " (Ex-ante, DHIS2, MSC, donor exports…)", " (Ex-ante, DHIS2, MSC, exportaciones para donantes…)")}
        </div>
      </div>
    );
  }

  // ── Étape 5 : Done ────────────────────────────────────────────────────
  function StepDone({ lang, appliedTemplate, templates }) {
    const tpl = templates && templates.find((t) => t.code === appliedTemplate);
    const tplName = tpl ? ((lang === "es" ? (tpl.name_es != null ? tpl.name_es : tpl.name_en) : lang === "fr" ? tpl.name_fr : tpl.name_en)) : (window.L("Configuration vide", "Empty setup", "Configuración vacía"));
    return (
      <div>
        <div style={{ fontSize: 56, marginBottom: 12, textAlign: "center" }}>🎉</div>
        <h2 style={{ fontSize: 24, fontWeight: 800, textAlign: "center", margin: "0 0 8px", color: "#0f172a" }}>
          {window.L("Vous êtes prêt !", "You're ready!", "¡Está listo!")}
        </h2>
        <p style={{ fontSize: 14, color: "#475569", textAlign: "center", margin: "0 auto 26px", maxWidth: 480 }}>
          {window.L(`Votre organisation est configurée avec « ${tplName} ». Voici 3 actions pour bien démarrer :`, `Your organization is set up with "${tplName}". Here are 3 actions to get going:`, `Su organización está configurada con «${tplName}». Aquí tiene 3 acciones para empezar bien:`)}
        </p>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {[
            { num: 1, emoji: "📁", fr: "Ouvrir votre premier projet", en: "Open your first project", es: "Abrir tu primer proyecto", target: "projects" },
            { num: 2, emoji: "📊", fr: "Saisir une première valeur d'indicateur", en: "Enter your first indicator value", es: "Introducir un primer valor de indicador", target: "indicators" },
            { num: 3, emoji: "📱", fr: "Installer l'app mobile (collecte terrain)", en: "Install the mobile app (field collection)", es: "Instalar la app móvil (recolección en terreno)", target: "mobile" },
          ].map((a) => (
            <button key={a.num}
              onClick={() => { if (window.__navigate) window.__navigate(a.target); }}
              style={{ padding: "14px 16px", border: "1px solid #e2e8f0", borderRadius: 10, background: "white", cursor: "pointer", textAlign: "left", display: "flex", alignItems: "center", gap: 14 }}>
              <span style={{ background: "#0f766e", color: "white", width: 28, height: 28, borderRadius: 14, display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 800 }}>
                {a.num}
              </span>
              <span style={{ fontSize: 22 }}>{a.emoji}</span>
              <span style={{ flex: 1, fontSize: 14, fontWeight: 600, color: "#0f172a" }}>
                {(lang === "es" ? (a.es != null ? a.es : a.en) : lang === "fr" ? a.fr : a.en)}
              </span>
              <span style={{ color: "#0f766e", fontWeight: 700 }}>→</span>
            </button>
          ))}
        </div>
      </div>
    );
  }

  window.OnboardingWizard = OnboardingWizard;

  // Petit chip "Démarrage X/5" affiché dans la sidebar tant que le wizard
  // n'est pas terminé ni dismissé. Cliquer le rouvre.
  function OnboardingChip({ lang, onResume }) {
    const { data: state, loading } = window.melr.useOnboardingState();
    if (loading || !state) return null;
    if (state.completed_at || state.dismissed) return null;
    const done = (state.completed_steps || []).length;
    return (
      <button onClick={onResume}
        title={window.L("Reprendre le wizard d'onboarding", "Resume onboarding wizard", "Reanudar el asistente de incorporación")}
        style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "6px 11px", borderRadius: 6,
          background: "linear-gradient(90deg,#fef3c7,#fffbeb)",
          border: "1px solid #fcd34d", color: "#78350f",
          fontSize: 11, fontWeight: 700, cursor: "pointer", width: "100%",
          marginTop: 6,
        }}>
        <span>🎯</span>
        <span style={{ flex: 1, textAlign: "left" }}>
          {window.L("Démarrage ", "Onboarding ", "Introducción ")}{done}/5
        </span>
        <span>→</span>
      </button>
    );
  }
  window.OnboardingChip = OnboardingChip;
})();
