/* global React, Icon, Button, RemoteCard, PageHead, Toolbar, StatusDot, Avatar, DATA */
// ============================================================
// Médias par device, avec SOUS-DOSSIERS + PREVIEW.
//  - L'owner (canEdit) prépare des dossiers (ex. "Photos de profil", "Reels")
//    et uploade des fichiers dedans, par iPhone.
//  - L'opérateur ouvre la section, navigue dans les dossiers, clique un média
//    pour le prévisualiser (photo/vidéo) puis l'envoie au téléphone en 1 clic
//    (HC BOX pushImage / pushVideo).
// ============================================================
function useMediaList(udid, live, dir) {
  const { useState, useEffect } = React;
  const [folders, setFolders] = useState([]);
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(false);
  const reload = async () => {
    if (!live || !udid) { setFolders([]); setFiles([]); return; }
    setLoading(true);
    const m = await window.Backend.media(udid, dir);
    setLoading(false);
    if (m) { setFolders(m.folders); setFiles(m.files); }
  };
  useEffect(() => { reload(); }, [udid, live, dir]);
  return { folders, files, loading, reload };
}

function fmtSize(n) { return n > 1048576 ? (n / 1048576).toFixed(1) + " Mo" : Math.max(1, Math.round(n / 1024)) + " Ko"; }

// ---- Aperçu plein écran (image ou vidéo) + bouton "Envoyer" ----
function PreviewModal({ udid, dir, f, onClose, onPush, pushing }) {
  if (!f) return null;
  const url = window.Backend.mediaUrl(udid, f.name, dir);
  const isImg = f.kind === "image";
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(4,7,15,.78)", backdropFilter: "blur(3px)", display: "grid", placeItems: "center", padding: 20 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: "min(560px, 94vw)", maxHeight: "92vh", display: "flex", flexDirection: "column", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", overflow: "hidden", boxShadow: "0 24px 70px rgba(0,0,0,.5)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "11px 14px", borderBottom: "1px solid var(--border)" }}>
          {React.createElement(Icon[isImg ? "image" : "play"], { size: 16, color: "var(--muted)" })}
          <div style={{ flex: 1, minWidth: 0, fontSize: 13.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={f.name}>{f.name}</div>
          <button onClick={onClose} style={{ width: 30, height: 30, display: "grid", placeItems: "center", borderRadius: 8, background: "var(--surface-3)", border: "1px solid var(--border)", color: "var(--muted)", cursor: "pointer" }}>{React.createElement(Icon.x, { size: 15 })}</button>
        </div>
        <div style={{ flex: 1, minHeight: 0, background: "#0b1020", display: "grid", placeItems: "center", padding: 10 }}>
          {isImg
            ? <img src={url} alt={f.name} style={{ maxWidth: "100%", maxHeight: "62vh", objectFit: "contain", borderRadius: 6 }} />
            : <video src={url} controls autoPlay style={{ maxWidth: "100%", maxHeight: "62vh", borderRadius: 6 }} />}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 14px", borderTop: "1px solid var(--border)" }}>
          <span className="mono" style={{ fontSize: 11, color: "var(--faint)", flex: 1 }}>{f.kind} · {fmtSize(f.size)}</span>
          <Button variant="primary" icon="send" onClick={() => onPush(f.name)} disabled={pushing === f.name}>
            {pushing === f.name ? "Envoi…" : "Envoyer au téléphone"}
          </Button>
        </div>
      </div>
    </div>
  );
}

// ---- Tuile dossier ----
function FolderTile({ folder, onOpen, onDelete }) {
  return (
    <div onClick={onOpen} style={{ cursor: "pointer", border: "1px solid var(--border)", borderRadius: 11, padding: "14px 12px", background: "var(--surface-2)", display: "flex", alignItems: "center", gap: 11, position: "relative" }}>
      <div style={{ width: 38, height: 38, borderRadius: 9, background: "var(--accent-soft)", display: "grid", placeItems: "center", color: "var(--accent)" }}>{React.createElement(Icon.grid, { size: 18 })}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={folder.name}>{folder.name}</div>
        <div className="mono" style={{ fontSize: 10, color: "var(--faint)" }}>{folder.count} fichier(s)</div>
      </div>
      {onDelete && <button onClick={e => { e.stopPropagation(); onDelete(folder.name); }} title="Supprimer le dossier" style={{ width: 26, height: 26, display: "grid", placeItems: "center", borderRadius: 7, background: "var(--surface-3)", border: "1px solid var(--border)", color: "var(--faint)", cursor: "pointer" }}>{React.createElement(Icon.x, { size: 12 })}</button>}
    </div>
  );
}

// ---- Tuile média (clic = aperçu) ----
function MediaTile({ udid, dir, f, onOpen, onPush, onDelete, pushing }) {
  const isImg = f.kind === "image";
  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: 11, overflow: "hidden", background: "var(--surface-2)" }}>
      <div onClick={() => onOpen(f)} title="Aperçu" style={{ cursor: "pointer", aspectRatio: "1", background: "#0b1020", display: "grid", placeItems: "center", overflow: "hidden", position: "relative" }}>
        {isImg
          ? <img src={window.Backend.mediaUrl(udid, f.name, dir)} alt={f.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          : React.createElement(Icon.play, { size: 26, color: "var(--muted)" })}
        <div style={{ position: "absolute", top: 6, right: 6, padding: "2px 6px", borderRadius: 6, background: "rgba(4,7,15,.6)", color: "#fff", fontSize: 9.5 }}>{isImg ? "photo" : "vidéo"}</div>
      </div>
      <div style={{ padding: "7px 8px" }}>
        <div style={{ fontSize: 11.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={f.name}>{f.name}</div>
        <div className="mono" style={{ fontSize: 9.5, color: "var(--faint)", marginBottom: 6 }}>{fmtSize(f.size)}</div>
        <div style={{ display: "flex", gap: 5 }}>
          <button onClick={() => onPush(f.name)} disabled={pushing === f.name} style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 5, padding: "6px", borderRadius: 7, background: "var(--accent-soft)", border: "1px solid var(--accent-line)", color: "var(--accent)", fontSize: 11, fontWeight: 600, cursor: "pointer" }}>
            {React.createElement(Icon.send, { size: 12 })}{pushing === f.name ? "…" : "Envoyer"}
          </button>
          {onDelete && <button onClick={() => onDelete(f.name)} title="Supprimer" style={{ width: 28, display: "grid", placeItems: "center", borderRadius: 7, background: "var(--surface-3)", border: "1px solid var(--border)", color: "var(--faint)", cursor: "pointer" }}>{React.createElement(Icon.x, { size: 12 })}</button>}
        </div>
      </div>
    </div>
  );
}

// Cœur réutilisable : navigation dossiers + upload + grille + aperçu + envoi.
function MediaGrid({ device, canEdit, cols = 3 }) {
  const { useState, useRef } = React;
  const live = !!(device && device.live && device.udid);
  const [dir, setDir] = useState("");
  const { folders, files, loading, reload } = useMediaList(device && device.udid, live, dir);
  const [toast, setToast] = useState("");
  const [pushing, setPushing] = useState(null);
  const [busy, setBusy] = useState(false);
  const [preview, setPreview] = useState(null);
  const fileRef = useRef(null);
  const flash = (t) => { setToast(t); setTimeout(() => setToast(""), 2600); };

  // reset le dossier courant si on change d'iPhone
  React.useEffect(() => { setDir(""); }, [device && device.udid]);

  if (!live) return (
    <div style={{ padding: "16px", borderRadius: 11, background: "var(--surface-2)", border: "1px dashed var(--border-2)", color: "var(--faint)", fontSize: 12.5, textAlign: "center" }}>
      {React.createElement(Icon.lock, { size: 18 })}<div style={{ marginTop: 6 }}>Médias indisponibles — device non relié au backend.</div>
    </div>
  );

  const onPick = async (e) => {
    const fs = [...e.target.files]; if (!fs.length) return;
    setBusy(true);
    for (const f of fs) await window.Backend.uploadMedia(device.udid, f, dir);
    setBusy(false); flash(`${fs.length} fichier(s) ajouté(s)`); reload(); e.target.value = "";
  };
  const push = async (name) => {
    setPushing(name);
    const r = await window.Backend.pushMedia(device.udid, name, dir);
    setPushing(null);
    const ok = r && r.result && r.result.StatusCode === 200;
    flash(ok ? "Envoyé au téléphone ✓" : "Échec de l'envoi");
    if (ok) setPreview(null);
  };
  const del = async (name) => { await window.Backend.delMedia(device.udid, name, dir); reload(); };
  const delDir = async (name) => { await window.Backend.delFolder(device.udid, (dir ? dir + "/" : "") + name); reload(); };
  const newFolder = async () => {
    const name = window.prompt("Nom du nouveau dossier (ex. Photos de profil, Reels) :");
    if (!name) return;
    await window.Backend.makeFolder(device.udid, name, dir);
    flash("Dossier créé"); reload();
  };

  const crumbs = dir ? dir.split("/") : [];
  const goTo = (i) => setDir(crumbs.slice(0, i + 1).join("/"));

  return (
    <div>
      {/* fil d'Ariane */}
      <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: 4, marginBottom: 10, fontSize: 12 }}>
        <button onClick={() => setDir("")} style={{ display: "flex", alignItems: "center", gap: 5, padding: "4px 8px", borderRadius: 7, background: dir ? "var(--surface-2)" : "var(--accent-soft)", border: "1px solid " + (dir ? "var(--border)" : "var(--accent-line)"), color: dir ? "var(--muted)" : "var(--accent)", cursor: "pointer", fontWeight: 600 }}>
          {React.createElement(Icon.grid, { size: 12 })} Dossiers
        </button>
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            <span style={{ color: "var(--faint)" }}>›</span>
            <button onClick={() => goTo(i)} style={{ padding: "4px 8px", borderRadius: 7, background: i === crumbs.length - 1 ? "var(--accent-soft)" : "var(--surface-2)", border: "1px solid " + (i === crumbs.length - 1 ? "var(--accent-line)" : "var(--border)"), color: i === crumbs.length - 1 ? "var(--accent)" : "var(--muted)", cursor: "pointer", fontWeight: 600 }}>{c}</button>
          </React.Fragment>
        ))}
      </div>

      {/* barre d'actions owner */}
      {canEdit && <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12, flexWrap: "wrap" }}>
        <input ref={fileRef} type="file" accept="image/*,video/*" multiple style={{ display: "none" }} onChange={onPick} />
        <Button variant="primary" icon="plus" onClick={() => fileRef.current && fileRef.current.click()}>{busy ? "Upload…" : "Ajouter des fichiers"}</Button>
        <Button variant="ghost" icon="grid" onClick={newFolder}>Nouveau dossier</Button>
        <span className="mono" style={{ fontSize: 11, color: "var(--faint)" }}>{folders.length} dossier(s) · {files.length} fichier(s)</span>
      </div>}

      {toast && <div style={{ marginBottom: 10, padding: "8px 11px", borderRadius: 8, background: "var(--accent-soft)", border: "1px solid var(--accent-line)", color: "var(--accent)", fontSize: 12 }}>{toast}</div>}

      {/* dossiers */}
      {folders.length > 0 && <div style={{ display: "grid", gridTemplateColumns: `repeat(${Math.max(1, Math.min(cols, 3))}, 1fr)`, gap: 9, marginBottom: 12 }}>
        {folders.map(fd => <FolderTile key={fd.name} folder={fd} onOpen={() => setDir((dir ? dir + "/" : "") + fd.name)} onDelete={canEdit ? delDir : null} />)}
      </div>}

      {/* fichiers */}
      {files.length === 0 && folders.length === 0
        ? <div style={{ color: "var(--faint)", fontSize: 12.5, padding: "14px 0", textAlign: "center" }}>{loading ? "Chargement…" : (canEdit ? "Vide — ajoutez des fichiers ou créez un dossier." : "Aucun média ici.")}</div>
        : files.length > 0 && <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 9 }}>
            {files.map(f => <MediaTile key={f.name} udid={device.udid} dir={dir} f={f} onOpen={setPreview} onPush={push} onDelete={canEdit ? del : null} pushing={pushing} />)}
          </div>}

      <PreviewModal udid={device.udid} dir={dir} f={preview} onClose={() => setPreview(null)} onPush={push} pushing={pushing} />
    </div>
  );
}

// Carte "Médias" côté opérateur (dans la télécommande, sous Saisie texte).
// Section repliée par défaut : un clic l'agrandit, l'opérateur navigue puis envoie.
function MediaCard({ device }) {
  return (
    <RemoteCard title={window.t ? t("medias") : "Médias"} icon="image" collapsible startOpen={false}>
      <MediaGrid device={device} canEdit={false} cols={2} />
    </RemoteCard>
  );
}

// Page "Dossiers" côté admin : un espace de médias par iPhone (owner = canEdit).
function AdminFolders() {
  const { useState } = React;
  const farm = useLiveDevices();
  const isLive = farm.online;
  const devices = (isLive && farm.list) ? farm.list : [];
  const [sel, setSel] = useState(null);
  const current = devices.find(d => d.id === sel) || devices[0];
  if (!isLive) return (
    <div>
      <PageHead title="Dossiers" sub="parc non synchronisé" />
      <SyncNotice online={false} ready={farm.ready} variant="admin" onSync={farm.refresh} />
    </div>
  );
  return (
    <div>
      <PageHead title="Dossiers" sub="● LIVE · médias par iPhone — créez des dossiers (Photos de profil, Reels…) puis uploadez" />
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 16 }} className="ov-grid">
        {/* liste des iPhones */}
        <div style={{ display: "grid", gap: 6, alignContent: "start" }}>
          {devices.map(d => (
            <button key={d.id} onClick={() => setSel(d.id)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 10, textAlign: "left",
              background: (current && current.id === d.id) ? "var(--accent-soft)" : "var(--surface-2)", border: "1px solid " + ((current && current.id === d.id) ? "var(--accent-line)" : "var(--border)"), cursor: "pointer" }}>
              {React.createElement(Icon.phone, { size: 16, color: "var(--muted)" })}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{d.tag}</div>
                <div className="mono" style={{ fontSize: 10, color: "var(--faint)" }}>{d.pool || d.name}</div>
              </div>
              <StatusDot status={d.status} />
            </button>
          ))}
        </div>
        {/* médias du device sélectionné */}
        <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", padding: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
            <div style={{ fontSize: 15, fontWeight: 700 }}>{current ? current.tag : "—"}</div>
            <span className="mono" style={{ fontSize: 11, color: "var(--faint)" }}>{current ? current.udid : ""}</span>
          </div>
          {current ? <MediaGrid device={current} canEdit={true} cols={4} /> : <div style={{ color: "var(--faint)" }}>Aucun device.</div>}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MediaGrid, MediaCard, AdminFolders });
