/* global React, Icon, Button, PageHead, Modal */
// ============================================================
// Phase Builder — éditeur de layout de panel par phase
// ============================================================

const PHASE_LAYOUT_KEY = (p) => `phonelabs.phase_layout.v3.${p}`;
const CUSTOM_PHASES_KEY = "phonelabs.custom_phases";

const BLOCK_CATALOG = [
  { id: "creation_form",   emoji: "📝", label: "Formulaire création",    col: "left",  desc: "Nom, username, password, TOTP, téléphone" },
  { id: "sop_steps",       emoji: "✅", label: "Étapes SOP",             col: "left",  desc: "Liste de cases à cocher de la SOP active" },
  { id: "ip_rotation",     emoji: "🔄", label: "Rotation d'IP",          col: "right", desc: "Changer l'IP via proxy rotatif (inclus dans Télécommande création)" },
  { id: "number_request",  emoji: "📞", label: "Demande de numéro",      col: "right", desc: "Commander un numéro HeroSMS / 5sim (inclus dans Télécommande création)" },
  { id: "twofa_slide",     emoji: "🔐", label: "2FA / TOTP",             col: "right", desc: "Configurer la double authentification (inclus dans Télécommande création)" },
  { id: "account_panel",   emoji: "📱", label: "Infos compte iPhone",    col: "left",  desc: "Comptes IG liés à cet iPhone + bloc-note" },
  { id: "my_tasks",        emoji: "📋", label: "Tâches assignées",       col: "left",  desc: "Missions du jour assignées à cet iPhone" },
  { id: "action_log",      emoji: "📜", label: "Journal d'actions",      col: "left",  desc: "Historique des actions effectuées" },
  { id: "logs_panel",      emoji: "🗂", label: "Logs / Historique",      col: "left",  desc: "Logs détaillés de l'iPhone" },
  { id: "remote",          emoji: "🎮", label: "Télécommande",           col: "right", desc: "Boutons swipe, tap, home, volume…" },
  { id: "text_send",       emoji: "⌨️", label: "Saisie de texte",        col: "right", desc: "Clavier virtuel — envoie du texte au champ actif" },
  { id: "media_send",      emoji: "🖼", label: "Envoi de médias",        col: "right", desc: "Envoyer photos/vidéos sur le téléphone" },
  { id: "creation_remote", emoji: "🚀", label: "Télécommande création",  col: "right", desc: "Actions rapides mode création de compte" },
];

const DEFAULT_LAYOUTS = {
  // creation_remote contient déjà IpRotation + NumberSlide + TwoFASlide en interne
  creation_compte: { left: ["creation_form", "sop_steps"], right: ["creation_remote"] },
  echauffement:    { left: ["account_panel", "my_tasks", "action_log"], right: ["remote", "text_send"] },
  publication:     { left: ["account_panel", "my_tasks"], right: ["remote", "text_send", "media_send"] },
};

function loadLayout(phase) {
  try { const r = localStorage.getItem(PHASE_LAYOUT_KEY(phase)); if (r) return JSON.parse(r); } catch (_) {}
  return DEFAULT_LAYOUTS[phase] || { left: [], right: [] };
}
function persistLayout(phase, layout) {
  try { localStorage.setItem(PHASE_LAYOUT_KEY(phase), JSON.stringify(layout)); } catch (_) {}
}
function loadCustomPhases() {
  try { return JSON.parse(localStorage.getItem(CUSTOM_PHASES_KEY) || "[]"); } catch (_) { return []; }
}
function persistCustomPhases(arr) {
  try { localStorage.setItem(CUSTOM_PHASES_KEY, JSON.stringify(arr)); } catch (_) {}
}

// Exposed for device_view
window.getPhaseLayout = loadLayout;

// ---- Phone mockup ------------------------------------------------
function PhoneMockup({ leftCount, rightCount }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
      <div style={{
        width: 240, height: 460, borderRadius: 46, border: "3px solid var(--border)",
        background: "var(--surface)", position: "relative", boxShadow: "0 8px 32px rgba(0,0,0,.18)",
        display: "flex", flexDirection: "column", alignItems: "center", overflow: "hidden",
      }}>
        {/* notch */}
        <div style={{ width: 72, height: 20, background: "var(--bg)", borderRadius: "0 0 18px 18px", marginTop: 0, zIndex: 2 }} />
        {/* screen content */}
        <div style={{ flex: 1, width: "100%", padding: "10px 12px", display: "flex", flexDirection: "column", gap: 6 }}>
          {Array.from({ length: Math.min(leftCount + rightCount, 7) }).map((_, i) => (
            <div key={i} style={{ height: 13, borderRadius: 6, background: i % 2 === 0 ? "var(--accent-soft)" : "var(--surface-2)", opacity: 0.5 + i * 0.05 }} />
          ))}
        </div>
        {/* home bar */}
        <div style={{ width: 60, height: 5, background: "var(--border)", borderRadius: 99, marginBottom: 12 }} />
      </div>
      <div style={{ fontSize: 11, color: "var(--faint)", textAlign: "center" }}>
        <div>← {leftCount} bloc{leftCount !== 1 ? "s" : ""}</div>
        <div>{rightCount} bloc{rightCount !== 1 ? "s" : ""} →</div>
      </div>
    </div>
  );
}

// ---- Block chip (draggable, in column or palette) -----------------
function BlockChip({ block, placed, colSide, onRemove, dragHandlers, isDragging }) {
  const bg = placed ? "var(--surface)" : "var(--surface-2)";
  const borderColor = placed ? "var(--accent-line)" : "var(--border)";
  return (
    <div
      draggable
      {...dragHandlers}
      style={{
        display: "flex", alignItems: "center", gap: 8,
        padding: placed ? "9px 12px" : "7px 11px",
        borderRadius: 10, border: `1px solid ${borderColor}`,
        background: bg, cursor: "grab", userSelect: "none",
        opacity: isDragging ? 0.35 : 1,
        transition: "opacity .15s",
      }}
    >
      <span style={{ fontSize: placed ? 16 : 14, flex: "none" }}>{block.emoji}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{block.label}</div>
        {placed && <div style={{ fontSize: 11, color: "var(--faint)", marginTop: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{block.desc}</div>}
      </div>
      {placed && (
        <button onClick={e => { e.stopPropagation(); onRemove && onRemove(); }}
          title="Retirer" style={{ background: "none", border: "none", color: "var(--faint)", cursor: "pointer", fontSize: 14, padding: 2, lineHeight: 1, flex: "none" }}>✕</button>
      )}
    </div>
  );
}

// ---- Drop zone line between blocks --------------------------------
function DropZone({ active, onDragOver, onDrop, onDragLeave }) {
  return (
    <div
      onDragOver={onDragOver}
      onDrop={onDrop}
      onDragLeave={onDragLeave}
      style={{
        height: active ? 28 : 6,
        borderRadius: 6,
        background: active ? "var(--accent-soft)" : "transparent",
        border: active ? "2px dashed var(--accent)" : "2px dashed transparent",
        transition: "all .12s",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}
    >
      {active && <span style={{ fontSize: 10.5, color: "var(--accent)", fontWeight: 700 }}>Déposer ici</span>}
    </div>
  );
}

// ---- Column with drop support ------------------------------------
function BuilderColumn({ col, blocks, dragging, dragOver, onDragOverZone, onDropZone, onDragLeave, onStartDrag, onRemove }) {
  const catalog = BLOCK_CATALOG;
  const label = col === "left" ? "← Gauche" : "Droite →";
  const accent = col === "left" ? "var(--accent)" : "#a78bfa";
  const colDragOver = dragOver && dragOver.col === col;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 0, minHeight: 280 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: accent, letterSpacing: ".06em", textTransform: "uppercase" }}>{label}</span>
        <span style={{ fontSize: 11, color: "var(--faint)", fontWeight: 500 }}>{blocks.length} bloc{blocks.length !== 1 ? "s" : ""}</span>
      </div>
      <div style={{ flex: 1, background: "var(--surface)", border: `1px dashed ${colDragOver ? accent : "var(--border)"}`, borderRadius: 14, padding: "10px 10px", display: "flex", flexDirection: "column", gap: 0, transition: "border-color .15s", minHeight: 240 }}>
        {/* drop zone avant le 1er bloc */}
        <DropZone
          active={colDragOver && dragOver.idx === 0}
          onDragOver={e => { e.preventDefault(); onDragOverZone(col, 0); }}
          onDrop={e => { e.preventDefault(); onDropZone(col, 0); }}
          onDragLeave={onDragLeave}
        />
        {blocks.length === 0 && !colDragOver && (
          <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--faint)", fontSize: 12, padding: "20px 0" }}>
            Glisse des blocs ici
          </div>
        )}
        {blocks.map((id, i) => {
          const block = catalog.find(b => b.id === id);
          if (!block) return null;
          return (
            <div key={id}>
              <BlockChip
                block={block}
                placed
                colSide={col}
                isDragging={dragging && dragging.id === id && dragging.fromCol === col}
                onRemove={() => onRemove(col, i)}
                dragHandlers={{
                  onDragStart: e => { e.dataTransfer.effectAllowed = "move"; onStartDrag({ id, fromCol: col, fromIdx: i }); },
                  onDragEnd: () => onDragLeave(),
                }}
              />
              <DropZone
                active={colDragOver && dragOver.idx === i + 1}
                onDragOver={e => { e.preventDefault(); onDragOverZone(col, i + 1); }}
                onDrop={e => { e.preventDefault(); onDropZone(col, i + 1); }}
                onDragLeave={onDragLeave}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ---- Main Phase Builder ------------------------------------------
function PhaseBuilder() {
  const { useState, useRef, useEffect } = React;

  const BUILTIN_PHASES = [
    { value: "creation_compte", label: "📱 Création de compte" },
    { value: "echauffement",    label: "🔥 Échauffement" },
    { value: "publication",     label: "🚀 Publication" },
  ];

  const [customPhases, setCustomPhases] = useState(loadCustomPhases);
  const allPhases = [...BUILTIN_PHASES, ...customPhases];
  const [phase, setPhase] = useState("creation_compte");
  const [layout, setLayout] = useState(() => loadLayout("creation_compte"));
  const [saved, setSaved] = useState(false);
  const [newPhaseName, setNewPhaseName] = useState("");
  const [addingPhase, setAddingPhase] = useState(false);

  // drag state
  const dragItem = useRef(null); // { id, fromCol, fromIdx }
  const [dragging, setDragging] = useState(null);
  const [dragOver, setDragOver] = useState(null); // { col, idx }

  // reload layout when phase changes
  const switchPhase = (p) => { setPhase(p); setLayout(loadLayout(p)); setSaved(false); };

  // palette = blocks not placed in either column
  const placed = new Set([...layout.left, ...layout.right]);
  const palette = BLOCK_CATALOG.filter(b => !placed.has(b.id));

  const startDrag = (info) => { dragItem.current = info; setDragging(info); };

  const doDragOver = (col, idx) => {
    const d = dragItem.current;
    if (!d) return;
    // si même colonne même position ou juste après soi-même → skip
    if (d.fromCol === col && (d.fromIdx === idx || d.fromIdx + 1 === idx)) return;
    setDragOver({ col, idx });
  };

  const doDrop = (col, insertAt) => {
    const d = dragItem.current;
    if (!d) { setDragOver(null); return; }
    setLayout(prev => {
      const next = { left: [...prev.left], right: [...prev.right] };
      // retirer de la source
      if (d.fromCol === "left" || d.fromCol === "right") {
        next[d.fromCol] = next[d.fromCol].filter((_, i) => i !== d.fromIdx);
        if (d.fromCol === col && d.fromIdx < insertAt) insertAt = Math.max(0, insertAt - 1);
      }
      // insérer à la cible
      next[col].splice(insertAt, 0, d.id);
      return next;
    });
    dragItem.current = null;
    setDragging(null);
    setDragOver(null);
  };

  const clearDrag = () => { setDragOver(null); };

  const removeBlock = (col, idx) => {
    setLayout(prev => {
      const next = { ...prev, [col]: prev[col].filter((_, i) => i !== idx) };
      return next;
    });
  };

  const addFromPalette = (id, col) => {
    if (placed.has(id)) return;
    setLayout(prev => ({ ...prev, [col]: [...prev[col], id] }));
  };

  const save = () => {
    persistLayout(phase, layout);
    window.getPhaseLayout = loadLayout; // refresh
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  const resetLayout = () => {
    const def = DEFAULT_LAYOUTS[phase] || { left: [], right: [] };
    setLayout(def);
    setSaved(false);
  };

  const addPhase = () => {
    const label = newPhaseName.trim();
    if (!label) return;
    const value = label.toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, "");
    if (allPhases.some(p => p.value === value)) { setNewPhaseName(""); setAddingPhase(false); return; }
    const entry = { value, label: "✨ " + label };
    const next = [...customPhases, entry];
    setCustomPhases(next);
    persistCustomPhases(next);
    setNewPhaseName(""); setAddingPhase(false);
    switchPhase(value);
  };

  const deleteCustomPhase = (val) => {
    const next = customPhases.filter(p => p.value !== val);
    setCustomPhases(next);
    persistCustomPhases(next);
    if (phase === val) switchPhase("creation_compte");
  };

  const curPhaseLabel = (allPhases.find(p => p.value === phase) || {}).label || phase;

  return (
    <div style={{ maxWidth: "100%", padding: "28px 32px" }}>
      {/* Header */}
      <PageHead title="Phase Builder" icon="grid" subtitle="Configure le layout gauche / droite de chaque phase iPhone — glisse les blocs." />

      {/* Phase selector */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "20px 0 24px", flexWrap: "wrap" }}>
        {allPhases.map(p => {
          const isCustom = customPhases.some(c => c.value === p.value);
          return (
            <div key={p.value} style={{ position: "relative" }}>
              <button
                onClick={() => switchPhase(p.value)}
                style={{
                  padding: "8px 18px", borderRadius: 99,
                  border: "1px solid " + (phase === p.value ? "var(--accent)" : "var(--border)"),
                  background: phase === p.value ? "var(--accent-soft)" : "var(--surface)",
                  color: phase === p.value ? "var(--accent)" : "var(--muted)",
                  fontWeight: 700, fontSize: 13, cursor: "pointer",
                  paddingRight: isCustom ? 30 : 18,
                }}
              >{p.label}</button>
              {isCustom && (
                <button onClick={() => deleteCustomPhase(p.value)}
                  title="Supprimer cette phase"
                  style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", background: "none", border: "none", color: "var(--faint)", cursor: "pointer", fontSize: 11, padding: 0, lineHeight: 1 }}>✕</button>
              )}
            </div>
          );
        })}
        {addingPhase ? (
          <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
            <input autoFocus value={newPhaseName} onChange={e => setNewPhaseName(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") addPhase(); if (e.key === "Escape") setAddingPhase(false); }}
              placeholder="Nom de la phase…"
              style={{ padding: "7px 12px", borderRadius: 8, border: "1px solid var(--accent)", background: "var(--surface)", color: "var(--text)", fontSize: 13, outline: "none", width: 160 }} />
            <button onClick={addPhase} style={{ padding: "7px 14px", borderRadius: 8, background: "var(--accent)", color: "#06281c", fontWeight: 700, fontSize: 13, border: "none", cursor: "pointer" }}>OK</button>
            <button onClick={() => setAddingPhase(false)} style={{ background: "none", border: "none", color: "var(--faint)", cursor: "pointer", fontSize: 13 }}>Annuler</button>
          </div>
        ) : (
          <button onClick={() => setAddingPhase(true)}
            style={{ padding: "8px 14px", borderRadius: 99, border: "1px dashed var(--border)", background: "none", color: "var(--faint)", fontSize: 13, cursor: "pointer" }}>
            + Nouvelle phase
          </button>
        )}
        <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" }}>
          {DEFAULT_LAYOUTS[phase] && (
            <button onClick={resetLayout} style={{ padding: "8px 14px", borderRadius: 9, border: "1px solid var(--border)", background: "var(--surface)", color: "var(--muted)", fontSize: 13, cursor: "pointer" }}>
              Réinitialiser
            </button>
          )}
          {saved && <span style={{ color: "var(--accent)", fontSize: 13, fontWeight: 700 }}>✓ Sauvegardé</span>}
          <button onClick={save}
            style={{ padding: "9px 22px", borderRadius: 9, background: "var(--accent)", color: "#06281c", fontWeight: 700, fontSize: 13.5, border: "none", cursor: "pointer" }}>
            Enregistrer
          </button>
        </div>
      </div>

      {/* Avertissement doublons */}
      {(() => {
        const all = [...layout.left, ...layout.right];
        const hasCreationRemote = all.includes("creation_remote");
        const conflicting = all.filter(id => ["ip_rotation", "number_request", "twofa_slide"].includes(id));
        const hasRemoteAndCreationRemote = all.includes("remote") && hasCreationRemote;
        const msgs = [];
        if (hasCreationRemote && conflicting.length > 0)
          msgs.push(`"Télécommande création" contient déjà : ${conflicting.map(id => ({ ip_rotation: "Rotation IP", number_request: "Demande de numéro", twofa_slide: "2FA/TOTP" })[id]).join(", ")}. Retire ces blocs pour éviter les doublons.`);
        if (hasRemoteAndCreationRemote)
          msgs.push(`"Télécommande" et "Télécommande création" sont incompatibles — utilise l'un ou l'autre.`);
        if (!msgs.length) return null;
        return (
          <div style={{ background: "rgba(251,146,60,.1)", border: "1px solid rgba(251,146,60,.4)", borderRadius: 10, padding: "10px 16px", marginBottom: 18, display: "flex", gap: 10, alignItems: "flex-start" }}>
            <span style={{ fontSize: 18, flex: "none" }}>⚠️</span>
            <div style={{ fontSize: 12.5, color: "#fb923c", lineHeight: 1.7 }}>{msgs.map((m, i) => <div key={i}>{m}</div>)}</div>
          </div>
        );
      })()}

      {/* Builder grid */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 280px 1fr", gap: 36, alignItems: "start" }}>
        {/* Colonne gauche */}
        <BuilderColumn
          col="left"
          blocks={layout.left}
          dragging={dragging}
          dragOver={dragOver}
          onDragOverZone={doDragOver}
          onDropZone={doDrop}
          onDragLeave={clearDrag}
          onStartDrag={startDrag}
          onRemove={removeBlock}
        />

        {/* Centre : téléphone */}
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 18, paddingTop: 34 }}>
          <PhoneMockup leftCount={layout.left.length} rightCount={layout.right.length} />
          <div style={{ fontSize: 11, color: "var(--faint)", textAlign: "center", lineHeight: 1.6 }}>
            Phase active :<br />
            <span style={{ color: "var(--text)", fontWeight: 700 }}>{curPhaseLabel}</span>
          </div>
        </div>

        {/* Colonne droite */}
        <BuilderColumn
          col="right"
          blocks={layout.right}
          dragging={dragging}
          dragOver={dragOver}
          onDragOverZone={doDragOver}
          onDropZone={doDrop}
          onDragLeave={clearDrag}
          onStartDrag={startDrag}
          onRemove={removeBlock}
        />
      </div>

      {/* Palette — blocs disponibles (non placés) */}
      <div style={{ marginTop: 28, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 16, padding: "16px 18px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
          {React.createElement(Icon.grid, { size: 15, color: "var(--muted)" })}
          <span style={{ fontSize: 12, fontWeight: 700, color: "var(--muted)", letterSpacing: ".06em", textTransform: "uppercase" }}>
            Blocs disponibles
          </span>
          <span style={{ fontSize: 11, color: "var(--faint)" }}>— glisse vers gauche ou droite, ou clique pour ajouter</span>
        </div>
        {palette.length === 0 ? (
          <div style={{ color: "var(--faint)", fontSize: 12.5, padding: "8px 0" }}>Tous les blocs sont placés.</div>
        ) : (
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {palette.map(block => (
              <div key={block.id} style={{ position: "relative" }}>
                <div
                  draggable
                  onDragStart={e => { e.dataTransfer.effectAllowed = "move"; startDrag({ id: block.id, fromCol: "palette", fromIdx: -1 }); }}
                  onDragEnd={clearDrag}
                  style={{ display: "flex", alignItems: "center", gap: 7, padding: "8px 12px", borderRadius: 10, border: "1px solid var(--border)", background: "var(--surface-2)", cursor: "grab", userSelect: "none" }}
                >
                  <span style={{ fontSize: 15 }}>{block.emoji}</span>
                  <div>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text)" }}>{block.label}</div>
                    <div style={{ fontSize: 11, color: "var(--faint)" }}>{block.desc}</div>
                  </div>
                </div>
                {/* boutons d'ajout rapide */}
                <div style={{ display: "flex", gap: 4, marginTop: 4, justifyContent: "center" }}>
                  <button onClick={() => addFromPalette(block.id, "left")}
                    style={{ fontSize: 11, padding: "3px 8px", borderRadius: 6, border: "1px solid var(--border)", background: "var(--surface)", color: "var(--accent)", cursor: "pointer", fontWeight: 700 }}>
                    ← Gauche
                  </button>
                  <button onClick={() => addFromPalette(block.id, "right")}
                    style={{ fontSize: 11, padding: "3px 8px", borderRadius: 6, border: "1px solid var(--border)", background: "var(--surface)", color: "#a78bfa", cursor: "pointer", fontWeight: 700 }}>
                    Droite →
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Drop zone global pour la palette — si on glisse depuis une colonne vers la palette */}
      <div style={{ marginTop: 12, height: 40, borderRadius: 10, border: "2px dashed transparent", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--faint)", fontSize: 12 }}
        onDragOver={e => { e.preventDefault(); }}
        onDrop={e => {
          e.preventDefault();
          const d = dragItem.current;
          if (!d || d.fromCol === "palette") return;
          setLayout(prev => ({
            ...prev,
            [d.fromCol]: prev[d.fromCol].filter((_, i) => i !== d.fromIdx),
          }));
          dragItem.current = null;
          setDragging(null);
          setDragOver(null);
        }}
      >
        Déposer ici pour retirer un bloc
      </div>
    </div>
  );
}

window.PhaseBuilder = PhaseBuilder;
