/* ============================================================
   ClientBase V2 · Module Acomptes (remplace Stock)
   ============================================================
   Modes d'affichage selon window.CB_FLAGS.acomptes_locked :
   - false (dev) → UI complète avec simulation de paiement
   - true (prod sans Stripe) → cadenas + wait-list
   ============================================================ */

const AppAcomptes = ({ data, actions, openModal }) => {
  const locked = !!(window.CB_FLAGS && window.CB_FLAGS.acomptes_locked);
  return locked
    ? <AcomptesLocked data={data}/>
    : <AcomptesSimulation data={data} actions={actions} openModal={openModal}/>;
};

/* ========== Mode LOCKED, cadenas + wait-list ========== */
const AcomptesLocked = ({ data }) => {
  const [submitted, setSubmitted] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const cu = (window.cbAuth && window.cbAuth.getCurrentUser && window.cbAuth.getCurrentUser()) || {};
  const userEmail = cu.email || "";

  const onInterest = async () => {
    if (loading || submitted) return;
    setLoading(true);
    try {
      let supaUid = null;
      if (window.cbSupabase && window.cbSupabase.auth) {
        const { data: s } = await window.cbSupabase.auth.getSession();
        supaUid = s?.session?.user?.id || null;
      }
      if (window.cbSupabase) {
        await window.cbSupabase.from("admin_events").insert([{
          user_id: supaUid,
          name: "acomptes_interest",
          props: { email: userEmail, source: "module_locked" },
          page_path: location.pathname,
        }]);
      }
      setSubmitted(true);
    } catch (e) { console.warn(e); }
    finally { setLoading(false); }
  };

  return (
    <div style={{ padding: 24, maxWidth: 720, margin: "0 auto" }}>
      <div className="card" style={{
        padding: "40px 28px", borderRadius: "var(--r-4)",
        textAlign: "center", position: "relative", overflow: "hidden",
      }}>
        {/* Halo décoratif */}
        <div style={{
          position: "absolute", top: -80, left: "50%", transform: "translateX(-50%)",
          width: 240, height: 240, borderRadius: "50%",
          background: "var(--accent-soft)", filter: "blur(60px)", opacity: 0.6,
          pointerEvents: "none",
        }}/>

        <div style={{
          position: "relative", display: "inline-flex", alignItems: "center", justifyContent: "center",
          width: 72, height: 72, borderRadius: "50%",
          background: "linear-gradient(135deg, var(--accent) 0%, oklch(58% 0.22 290) 100%)",
          color: "#fff", marginBottom: 18,
          boxShadow: "0 14px 30px -10px oklch(55% 0.22 278 / 0.45)",
        }}>
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
            <rect x="5" y="11" width="14" height="9" rx="2" stroke="currentColor" strokeWidth="1.8"/>
            <path d="M8 11V8a4 4 0 0 1 8 0v3" stroke="currentColor" strokeWidth="1.8"/>
          </svg>
        </div>

        <div style={{ position: "relative", fontSize: 11, fontWeight: 600, color: "var(--accent-ink)",
          textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8 }}>
          Arrive prochainement
        </div>
        <h2 style={{ position: "relative", fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em",
          margin: "0 0 10px", lineHeight: 1.2 }}>
          Module <em style={{ color: "var(--accent)", fontStyle: "italic", fontWeight: 540 }}>Acomptes</em>
        </h2>
        <p style={{ position: "relative", fontSize: 14.5, color: "var(--ink-2)", lineHeight: 1.6,
          maxWidth: 480, margin: "0 auto 22px" }}>
          Demandez un acompte à la réservation pour bloquer le créneau et réduire les no-show.
          Le module nécessite un compte de paiement sécurisé (Stripe), <strong>en cours d'intégration</strong>.
        </p>

        {/* Petits arguments */}
        <div style={{ position: "relative", display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
          gap: 10, marginBottom: 24, maxWidth: 580, marginLeft: "auto", marginRight: "auto" }}>
          {[
            { em: "🛡", t: "Moins de no-show", d: "Cliente engagée financièrement" },
            { em: "💸", t: "Cash flow", d: "Encaissement avant prestation" },
            { em: "🤝", t: "Souple", d: "Annulation 48h = remboursé" },
          ].map((c, i) => (
            <div key={i} style={{
              padding: "12px 14px", background: "var(--bg-alt)", border: "1px solid var(--line)",
              borderRadius: "var(--r-3)", textAlign: "left",
            }}>
              <div style={{ fontSize: 20, marginBottom: 4 }}>{c.em}</div>
              <div style={{ fontSize: 13.5, fontWeight: 580, color: "var(--ink)" }}>{c.t}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{c.d}</div>
            </div>
          ))}
        </div>

        {/* CTA */}
        {!submitted ? (
          <button
            className="btn btn-primary"
            onClick={onInterest}
            disabled={loading}
            style={{ position: "relative", gap: 9 }}
          >
            {loading ? "Enregistrement…" : "Me prévenir à la sortie"}
            <span style={{ fontSize: 16 }}>→</span>
          </button>
        ) : (
          <div style={{
            position: "relative",
            display: "inline-flex", alignItems: "center", gap: 9,
            padding: "11px 20px", background: "oklch(95% 0.06 150)",
            color: "oklch(38% 0.14 150)", borderRadius: 999,
            fontSize: 14, fontWeight: 580, border: "1px solid oklch(85% 0.08 150)",
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M5 12l5 5L20 7" stroke="currentColor" strokeWidth="2.4"
                strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            On vous prévient dès que c'est prêt
          </div>
        )}

        <div style={{ position: "relative", marginTop: 16, fontSize: 12, color: "var(--ink-4)" }}>
          Une question&nbsp;? <a href="mailto:clientbase.fr@gmail.com?subject=Acomptes%20—%20question"
            style={{ color: "var(--accent-ink)", fontWeight: 540 }}>nous écrire</a>
        </div>
      </div>
    </div>
  );
};

/* ========== Mode SIMULATION, UI complète fonctionnelle ========== */
const AcomptesSimulation = ({ data, actions, openModal }) => {
  const [userId, setUserId] = React.useState(null);
  const [settings, setSettings] = React.useState({
    enabled: false, percent: 30, min_amount: 50,
    refund_window_hrs: 48,
    policy_text: "Acompte non remboursable sauf annulation 48h avant.",
  });
  const [acomptes, setAcomptes] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [editing, setEditing] = React.useState(false);

  // Récupère le user_id Supabase au mount
  React.useEffect(() => {
    if (!window.cbSupabase || !window.cbSupabase.auth) { setLoading(false); return; }
    (async () => {
      const { data: s } = await window.cbSupabase.auth.getSession();
      const uid = s?.session?.user?.id || null;
      setUserId(uid);
      if (!uid) setLoading(false);
    })();
  }, []);

  // Load settings + acomptes depuis Supabase
  React.useEffect(() => {
    if (!window.cbSupabase || !userId) return;
    (async () => {
      try {
        const { data: s } = await window.cbSupabase
          .from("acompte_settings").select("*").eq("user_id", userId).maybeSingle();
        if (s) setSettings({
          enabled: !!s.enabled,
          percent: s.percent || 30,
          min_amount: +(s.min_amount || 50),
          refund_window_hrs: s.refund_window_hrs || 48,
          policy_text: s.policy_text || "",
        });
        const { data: list } = await window.cbSupabase
          .from("acomptes").select("*").eq("user_id", userId)
          .order("created_at", { ascending: false }).limit(50);
        setAcomptes(list || []);
      } catch (e) { console.warn(e); }
      finally { setLoading(false); }
    })();
  }, [userId]);

  const saveSettings = async () => {
    if (!window.cbSupabase || !userId) return;
    try {
      await window.cbSupabase.from("acompte_settings").upsert({
        user_id: userId,
        enabled: settings.enabled,
        percent: settings.percent,
        min_amount: settings.min_amount,
        refund_window_hrs: settings.refund_window_hrs,
        policy_text: settings.policy_text,
        updated_at: new Date().toISOString(),
      });
      setEditing(false);
    } catch (e) { console.warn(e); }
  };

  // Simuler un acompte (pour démo)
  const simulateAcompte = async () => {
    if (!window.cbSupabase || !userId) return;
    const total = 80;
    const deposit = Math.round(total * (settings.percent / 100));
    try {
      const { data: row } = await window.cbSupabase.from("acomptes").insert([{
        user_id: userId,
        amount_total: total,
        amount_deposit: deposit,
        amount_remaining: total - deposit,
        status: "paid",
        payment_method: "simulation",
        service_label: "Coupe + couleur",
        client_name: "Marie · simulation",
        paid_at: new Date().toISOString(),
      }]).select().single();
      if (row) setAcomptes(prev => [row, ...prev]);
    } catch (e) { console.warn(e); }
  };

  if (loading) return <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>Chargement…</div>;

  return (
    <div style={{ paddingBottom: 60, position: "relative" }}>
      {/* === Overlay « Arrive prochainement » === */}
      <div style={{
        position: "absolute", inset: 0, zIndex: 10,
        display: "flex", alignItems: "flex-start", justifyContent: "center",
        paddingTop: "16vh",
        pointerEvents: "none",
      }}>
        <div style={{
          pointerEvents: "auto",
          padding: "26px 32px",
          background: "var(--surface)",
          border: "1px solid var(--accent-soft-2)",
          borderRadius: 20,
          boxShadow: "0 24px 60px -20px rgba(15,18,30,0.3)",
          textAlign: "center", maxWidth: 380,
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 16, margin: "0 auto 14px",
            background: "linear-gradient(135deg, var(--accent) 0%, oklch(48% 0.20 300) 100%)",
            color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center",
            boxShadow: "0 14px 30px -10px var(--accent)",
            fontSize: 28,
          }}>💰</div>
          <h3 style={{
            margin: 0, fontFamily: "var(--ff-display)", fontSize: 22, fontWeight: 600,
            letterSpacing: "-0.025em", color: "var(--ink)",
          }}>
            Arrive prochainement
          </h3>
          <p style={{
            margin: "8px 0 0", fontSize: 13.5, color: "var(--ink-3)", lineHeight: 1.55,
          }}>
            Le module Acomptes est en cours de finalisation. Vous pourrez bientôt
            demander un acompte à la réservation pour bloquer le créneau et limiter
            les no-shows.
          </p>
        </div>
      </div>

      {/* Contenu de la page, flouté */}
      <div style={{ filter: "blur(4px)", pointerEvents: "none", userSelect: "none", opacity: 0.85 }}>

      {/* En-tête harmonisé (Factures / Acomptes / Stock) */}
      <div style={{ marginBottom: 18, display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
        <div>
          <h3 style={{ fontSize: 22, fontFamily: "var(--ff-display)", fontWeight: 580, letterSpacing: "-0.022em", margin: 0 }}>Vos acomptes</h3>
          <p style={{ fontSize: 14, color: "var(--ink-3)", marginTop: 5, lineHeight: 1.5, maxWidth: 560, margin: "5px 0 0" }}>
            Demandez un acompte à la réservation pour bloquer le créneau et limiter les no-shows.
          </p>
        </div>
        <div style={{ display: "flex", gap: 8, flexShrink: 0 }}>
          <button className="btn btn-ghost btn-sm cb-press-feedback"
            onClick={() => setEditing(!editing)}>
            <Icon name="settings" size={13}/> {editing ? "Fermer" : "Paramètres"}
          </button>
          <button className="btn btn-primary btn-sm cb-press-feedback" onClick={simulateAcompte}>
            <Icon name="plus" size={13}/> Nouvel acompte
          </button>
        </div>
      </div>

      {/* Settings panel (toggle) */}
      {editing && (
        <div className="card" style={{ padding: 22, marginBottom: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
            <label style={{ display: "inline-flex", alignItems: "center", gap: 9, cursor: "pointer", flex: 1 }}>
              <input type="checkbox" checked={settings.enabled}
                onChange={e => setSettings({ ...settings, enabled: e.target.checked })}
                style={{ width: 18, height: 18 }}/>
              <span style={{ fontSize: 14, fontWeight: 540 }}>
                {settings.enabled ? "Acompte activé pour mes prestations" : "Module désactivé"}
              </span>
            </label>
          </div>

          {settings.enabled && (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(180px,1fr))", gap: 14 }}>
              <div>
                <label style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 540, display: "block", marginBottom: 5 }}>
                  Pourcentage d'acompte
                </label>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <input type="number" min="0" max="100" value={settings.percent}
                    onChange={e => setSettings({ ...settings, percent: +e.target.value })}
                    style={{ flex: 1, padding: "10px 13px", border: "1px solid var(--line)",
                      borderRadius: 10, fontFamily: "inherit", fontSize: 14 }}/>
                  <span style={{ color: "var(--ink-3)", fontWeight: 540 }}>%</span>
                </div>
              </div>
              <div>
                <label style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 540, display: "block", marginBottom: 5 }}>
                  À partir de
                </label>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <input type="number" min="0" value={settings.min_amount}
                    onChange={e => setSettings({ ...settings, min_amount: +e.target.value })}
                    style={{ flex: 1, padding: "10px 13px", border: "1px solid var(--line)",
                      borderRadius: 10, fontFamily: "inherit", fontSize: 14 }}/>
                  <span style={{ color: "var(--ink-3)", fontWeight: 540 }}>€</span>
                </div>
              </div>
              <div>
                <label style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 540, display: "block", marginBottom: 5 }}>
                  Délai annulation = remboursé
                </label>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <input type="number" min="0" value={settings.refund_window_hrs}
                    onChange={e => setSettings({ ...settings, refund_window_hrs: +e.target.value })}
                    style={{ flex: 1, padding: "10px 13px", border: "1px solid var(--line)",
                      borderRadius: 10, fontFamily: "inherit", fontSize: 14 }}/>
                  <span style={{ color: "var(--ink-3)", fontWeight: 540 }}>h</span>
                </div>
              </div>
              <div style={{ gridColumn: "1 / -1" }}>
                <label style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 540, display: "block", marginBottom: 5 }}>
                  Texte de la politique d'annulation
                </label>
                <textarea value={settings.policy_text}
                  onChange={e => setSettings({ ...settings, policy_text: e.target.value })}
                  style={{ width: "100%", padding: "10px 13px", border: "1px solid var(--line)",
                    borderRadius: 10, fontFamily: "inherit", fontSize: 13, minHeight: 60, resize: "vertical" }}/>
              </div>
            </div>
          )}

          <div style={{ marginTop: 16, display: "flex", justifyContent: "flex-end", gap: 8 }}>
            <button className="btn btn-ghost" onClick={() => setEditing(false)}>Annuler</button>
            <button className="btn btn-primary" onClick={saveSettings}>Enregistrer</button>
          </div>
        </div>
      )}

      {/* KPIs compacts, style tableau de bord */}
      {acomptes.length > 0 && (() => {
        const now = Date.now();
        const monthAgo = now - 30 * 86400000;
        const monthOnes = acomptes.filter(a => new Date(a.created_at).getTime() > monthAgo);
        const totalBlocked = monthOnes
          .filter(a => a.status === "paid" || a.status === "completed")
          .reduce((s, a) => s + (+a.amount_deposit || 0), 0);
        const forfeited = acomptes.filter(a => a.status === "forfeited").length;
        const pendingNow = acomptes.filter(a => a.status === "pending").length;
        return (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10, marginBottom: 14 }}>
            {[
              { label: "Total bloqué (30j)", value: `${Math.round(totalBlocked).toLocaleString("fr-FR")} €`, tone: "var(--accent)" },
              { label: "Acomptes en cours", value: pendingNow, tone: "oklch(60% 0.17 30)" },
              { label: "No-shows conservés", value: forfeited, tone: "oklch(55% 0.18 25)" },
            ].map(k => (
              <div key={k.label} style={{
                padding: "12px 14px", background: "var(--surface)",
                border: "1px solid var(--line)", borderRadius: 12,
                borderLeft: `3px solid ${k.tone}`,
              }}>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 19, fontWeight: 600, letterSpacing: "-0.025em", color: "var(--ink)" }}>{k.value}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{k.label}</div>
              </div>
            ))}
          </div>
        );
      })()}

      {/* Liste */}
      <div style={{ marginBottom: 14, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <h3 style={{ margin: 0, fontSize: 15, fontWeight: 580 }}>Acomptes récents</h3>
        <span style={{ fontSize: 12, color: "var(--ink-4)" }}>{acomptes.length} au total</span>
      </div>

      {acomptes.length === 0 ? (
        <div style={{
          padding: "40px 20px", textAlign: "center",
          background: "var(--bg-alt)", border: "1px dashed var(--line-strong)",
          borderRadius: 12, color: "var(--ink-3)",
        }}>
          <div style={{ fontSize: 32, marginBottom: 8 }}>💰</div>
          <div style={{ fontSize: 14.5, fontWeight: 520, color: "var(--ink-2)" }}>Vous n'avez aucun acompte pour l'instant</div>
          <div style={{ fontSize: 13, marginTop: 6 }}>
            {settings.enabled
              ? "Les acomptes apparaîtront ici dès qu'une cliente réserve."
              : "Activez le module dans Paramètres pour commencer à en demander."}
          </div>
        </div>
      ) : (
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          {acomptes.map((a, i) => <AcompteRow key={a.id} item={a} last={i === acomptes.length - 1}/>)}
        </div>
      )}
      </div>{/* fin contenu flouté */}
    </div>
  );
};

const AcompteRow = ({ item, last }) => {
  const statusColor = {
    paid: "#34C759", completed: "var(--ink-2)",
    pending: "#FF9500", refunded: "var(--ink-3)", forfeited: "#FF3B30",
  }[item.status] || "var(--ink-3)";
  const statusLabel = {
    paid: "Payé", completed: "Terminé", pending: "En attente",
    refunded: "Remboursé", forfeited: "Conservé",
  }[item.status] || item.status;
  return (
    <div style={{
      padding: "13px 16px", display: "grid",
      gridTemplateColumns: "1.4fr 90px 90px 90px",
      gap: 12, alignItems: "center", fontSize: 13,
      borderBottom: last ? "none" : "1px solid var(--line)",
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 540, color: "var(--ink)",
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {item.client_name || "Cliente"} {item.payment_method === "simulation" && (
            <span style={{ fontSize: 10, color: "var(--ink-4)", marginLeft: 4 }}>· sim</span>
          )}
        </div>
        <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2,
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {item.service_label || "Prestation"} · {new Date(item.created_at).toLocaleDateString("fr-FR",
            { day: "2-digit", month: "short" })}
        </div>
      </div>
      <div style={{ fontFamily: "var(--ff-text)", fontSize: 13, color: "var(--ink-2)",
        textAlign: "right" }}>{(+item.amount_total).toFixed(0)} €</div>
      <div style={{ fontFamily: "var(--ff-text)", fontSize: 13.5, color: "var(--accent)",
        fontWeight: 580, textAlign: "right" }}>+{(+item.amount_deposit).toFixed(0)} €</div>
      <div style={{ textAlign: "right" }}>
        <span style={{ display: "inline-flex", padding: "3px 9px",
          background: statusColor + "22", color: statusColor, borderRadius: 999,
          fontSize: 10.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
          {statusLabel}
        </span>
      </div>
    </div>
  );
};
