// =============================================================
// Project editor — right panel: Elements library (when that tool is
// active) or the Inspector for the current selection/slide.
// =============================================================
function ProjectRightPanel({
  activeTool, setActiveTool, selected, slide, insertElement,
  updateSelected, updateSlide, deleteSelected, duplicateSelected, reorderSelected, onPickAsset,
}) {
  if (activeTool === "elements" && !selected) {
    return <ElementsPanel onInsert={insertElement} onClose={() => setActiveTool("select")} />;
  }
  return (
    <Inspector
      selected={selected}
      slide={slide}
      updateSelected={updateSelected}
      updateSlide={updateSlide}
      deleteSelected={deleteSelected}
      duplicateSelected={duplicateSelected}
      reorderSelected={reorderSelected}
      onPickAsset={onPickAsset}
    />
  );
}

// =============================================================
// Elements panel — Shapes, Badges, and brand Stickers to drop in.
// =============================================================
const EL_DISPLAY = "ES Rebond Grotesque";
const EL_SHAPES = [
  { name: "Rectangle", preview: { borderRadius: 4, background: "#070707" }, cfg: { type: "shape", w: 320, h: 200, shape: "rect", fill: "#070707", borderRadius: 0 } },
  { name: "Rounded", preview: { borderRadius: 12, background: "#070707" }, cfg: { type: "shape", w: 320, h: 200, shape: "rect", fill: "#070707", borderRadius: 28 } },
  { name: "Circle", preview: { borderRadius: "50%", background: "#070707", width: 40, height: 40 }, cfg: { type: "shape", w: 240, h: 240, shape: "circle", fill: "#070707", borderRadius: 0 } },
  { name: "Pill", preview: { borderRadius: 999, background: "#070707", width: 54, height: 24 }, cfg: { type: "shape", w: 300, h: 96, shape: "rect", fill: "#070707", borderRadius: 100 } },
  { name: "Line", preview: { borderRadius: 999, background: "#070707", width: 54, height: 6 }, cfg: { type: "shape", w: 440, h: 8, shape: "rect", fill: "#070707", borderRadius: 4 } },
];
const EL_BADGES = [
  { content: "EPISODE", w: 200 },
  { content: "01", w: 110 },
  { content: "NEW", w: 130 },
  { content: "FLEXXIBLE BY DESIGN", w: 440 },
];
// True-vector SVGs — crisp at any size on canvas and in exports.
const EL_STICKERS = [
  { src: "assets/sticker-flexxi.svg", ar: 408 / 165, label: "FLEXXI" },
  { src: "assets/sticker-flexxible.svg", ar: 336 / 179, label: "Flexxi-ble" },
  { src: "assets/sticker-layers.svg", ar: 325 / 286, label: "Do It In Layers" },
  { src: "assets/sticker-xx.svg", ar: 192 / 146, label: "XX mark" },
  { src: "assets/flexxi-sticker-holo.png", ar: 415 / 158, label: "Holographic" },
  { src: "assets/xx-pattern.svg", ar: 1514 / 1011, label: "XX pattern", cover: true },
];

function ElementsPanel({ onInsert, onClose }) {
  return (
    <div className="editor-inspector">
      <div className="inspector-section" style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div className="inspector-label" style={{ marginBottom: 0 }}>Elements</div>
        <button className="btn btn-sm btn-ghost" style={{ padding: "5px 8px" }} onClick={onClose} title="Close">
          <Icons.X size={13} />
        </button>
      </div>

      <div className="inspector-section">
        <div className="inspector-label">Shapes</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
          {EL_SHAPES.map((s) => (
            <button key={s.name} className="elem-tile" title={s.name} onClick={() => onInsert(s.cfg)}>
              <div style={{ width: 44, height: 30, ...s.preview }} />
            </button>
          ))}
        </div>
      </div>

      <div className="inspector-section">
        <div className="inspector-label">Badges</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {EL_BADGES.map((b) => (
            <button
              key={b.content}
              className="badge-tile"
              onClick={() => onInsert({ type: "sticker", w: b.w, h: 72, content: b.content, fill: "#070707", color: "#FFFFFF", fontSize: 30, fontFamily: EL_DISPLAY, fontWeight: 700 })}
            >
              {b.content}
            </button>
          ))}
        </div>
      </div>

      <div className="inspector-section">
        <div className="inspector-label">Stickers</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          {EL_STICKERS.map((s) => (
            <button
              key={s.src}
              className="sticker-tile"
              title={s.label}
              onClick={() => onInsert({ type: "image", src: s.src, w: 360, h: Math.round(360 / s.ar), fit: s.cover ? "cover" : "contain", borderRadius: s.cover ? 16 : 0 })}
            >
              <img src={s.src} alt={s.label} draggable={false} style={{ maxWidth: "100%", maxHeight: 60, objectFit: "contain" }} />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// =============================================================
// Inspector
// =============================================================
function Inspector({ selected, slide, updateSelected, updateSlide, deleteSelected, duplicateSelected, reorderSelected, onPickAsset }) {
  // When nothing selected → slide settings
  if (!selected) {
    return (
      <div className="editor-inspector">
        <div className="inspector-section">
          <div className="inspector-label">Slide background</div>
          <ColorPicker
            value={slide.background}
            onChange={(c) => updateSlide({ background: c })}
            allowHolo
          />
        </div>
        <div className="inspector-section">
          <div className="inspector-label">Tip</div>
          <p style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5, margin: 0 }}>
            Click any element to edit it.
            <br />Double-click text to type.
            <br />Press <kbd style={{ background: "var(--surface)", padding: "2px 5px", border: "1px solid var(--line)", borderRadius: 4, fontSize: 11 }}>Delete</kbd> to remove.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="editor-inspector">
      <div className="inspector-section">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div className="inspector-label" style={{ marginBottom: 0 }}>
            {selected.type === "text" ? "Text" : selected.type === "image" ? "Image" : selected.type === "sticker" ? "Sticker" : "Shape"}
          </div>
          <div style={{ display: "flex", gap: 4 }}>
            <button className="btn btn-sm btn-ghost" style={{ padding: "5px 8px" }} onClick={duplicateSelected} title="Duplicate">
              <Icons.Copy size={13} />
            </button>
            <button className="btn btn-sm btn-ghost" style={{ padding: "5px 8px" }} onClick={deleteSelected} title="Delete">
              <Icons.Trash size={13} />
            </button>
          </div>
        </div>
      </div>

      {/* Stacking order — works for every element type (images included) */}
      <div className="inspector-section">
        <div className="inspector-label">Layer</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
          <button className="btn btn-sm btn-surface" onClick={() => reorderSelected("front")} title="Bring to front (⌘⇧])">To front</button>
          <button className="btn btn-sm btn-surface" onClick={() => reorderSelected("back")} title="Send to back (⌘⇧[)">To back</button>
          <button className="btn btn-sm btn-surface" onClick={() => reorderSelected("forward")} title="Bring forward (⌘])">Forward</button>
          <button className="btn btn-sm btn-surface" onClick={() => reorderSelected("backward")} title="Send backward (⌘[)">Backward</button>
        </div>
      </div>

      {/* TEXT properties */}
      {(selected.type === "text" || selected.type === "sticker") && (
        <>
          <div className="inspector-section">
            <div className="inspector-label">Content</div>
            <textarea
              className="input"
              value={selected.content || ""}
              onChange={(e) => updateSelected({ content: e.target.value })}
              placeholder="Type your text…"
              rows={selected.type === "sticker" ? 1 : 3}
              style={{ width: "100%", fontSize: 14, lineHeight: 1.4, resize: "vertical" }}
            />
            <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 6 }}>
              Tip: double-click the text on the canvas to edit it in place.
            </div>
          </div>

          <div className="inspector-section">
            <div className="inspector-label">Font</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {BRAND_FONTS.map((f) => (
                <button
                  key={f.family}
                  className={`font-pill ${selected.fontFamily === f.family ? "active" : ""}`}
                  style={{ fontFamily: `'${f.family}'` }}
                  onClick={() => updateSelected({ fontFamily: f.family, italic: f.family === "Instrument Serif" })}
                >
                  <div style={{ fontSize: 14, fontWeight: f.family === "Instrument Serif" ? 400 : 600, fontStyle: f.family === "Instrument Serif" ? "italic" : "normal" }}>
                    {f.label}
                  </div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)", fontFamily: "var(--font-ui)", fontStyle: "normal", marginTop: 2 }}>
                    {f.role}
                  </div>
                </button>
              ))}
            </div>
          </div>

          <div className="inspector-section">
            <div className="inspector-label">Size</div>
            <NumberInput
              value={selected.fontSize}
              min={8} max={500} step={2}
              onChange={(v) => updateSelected({ fontSize: v })}
            />
          </div>

          {selected.type === "text" && (
            <div className="inspector-section">
              <div className="inspector-label">Style</div>
              <div style={{ display: "flex", gap: 6 }}>
                <button
                  className="btn btn-sm btn-surface"
                  style={{ padding: "6px 10px", background: selected.fontWeight >= 700 ? "var(--ink)" : "var(--surface)", color: selected.fontWeight >= 700 ? "var(--surface)" : "var(--ink)" }}
                  onClick={() => updateSelected({ fontWeight: selected.fontWeight >= 700 ? 400 : 700 })}
                >
                  <Icons.Bold size={13} />
                </button>
                <button
                  className="btn btn-sm btn-surface"
                  style={{ padding: "6px 10px", background: selected.italic ? "var(--ink)" : "var(--surface)", color: selected.italic ? "var(--surface)" : "var(--ink)" }}
                  onClick={() => updateSelected({ italic: !selected.italic })}
                >
                  <Icons.Italic size={13} />
                </button>
                <button
                  className="btn btn-sm btn-surface"
                  style={{ padding: "6px 10px", background: selected.textAlign === "left" ? "var(--ink)" : "var(--surface)", color: selected.textAlign === "left" ? "var(--surface)" : "var(--ink)" }}
                  onClick={() => updateSelected({ textAlign: "left" })}
                >
                  <Icons.AlignLeft size={13} />
                </button>
                <button
                  className="btn btn-sm btn-surface"
                  style={{ padding: "6px 10px", background: selected.textAlign === "center" ? "var(--ink)" : "var(--surface)", color: selected.textAlign === "center" ? "var(--surface)" : "var(--ink)" }}
                  onClick={() => updateSelected({ textAlign: "center" })}
                >
                  <Icons.AlignCenter size={13} />
                </button>
                <button
                  className="btn btn-sm btn-surface"
                  style={{ padding: "6px 10px", background: selected.textAlign === "right" ? "var(--ink)" : "var(--surface)", color: selected.textAlign === "right" ? "var(--surface)" : "var(--ink)" }}
                  onClick={() => updateSelected({ textAlign: "right" })}
                >
                  <Icons.AlignRight size={13} />
                </button>
              </div>
            </div>
          )}

          <div className="inspector-section">
            <div className="inspector-label">Color</div>
            <ColorPicker value={selected.color} onChange={(c) => updateSelected({ color: c })} />
          </div>

          {selected.type === "sticker" && (
            <div className="inspector-section">
              <div className="inspector-label">Sticker fill</div>
              <ColorPicker value={selected.fill} onChange={(c) => updateSelected({ fill: c })} allowHolo />
            </div>
          )}
        </>
      )}

      {/* SHAPE properties */}
      {selected.type === "shape" && (
        <>
          <div className="inspector-section">
            <div className="inspector-label">Fill</div>
            <ColorPicker value={selected.fill} onChange={(c) => updateSelected({ fill: c })} allowHolo />
          </div>
          <div className="inspector-section">
            <div className="inspector-label">Corner radius</div>
            <NumberInput
              value={selected.borderRadius || 0}
              min={0} max={999} step={2}
              onChange={(v) => updateSelected({ borderRadius: v })}
            />
          </div>
          <div className="inspector-section">
            <div className="inspector-label">Shape</div>
            <div style={{ display: "flex", gap: 6 }}>
              <button className={`btn btn-sm btn-surface ${selected.shape === "rect" ? "" : ""}`}
                style={{ background: selected.shape !== "circle" ? "var(--ink)" : "var(--surface)", color: selected.shape !== "circle" ? "var(--surface)" : "var(--ink)" }}
                onClick={() => updateSelected({ shape: "rect" })}>Rect</button>
              <button className={`btn btn-sm btn-surface`}
                style={{ background: selected.shape === "circle" ? "var(--ink)" : "var(--surface)", color: selected.shape === "circle" ? "var(--surface)" : "var(--ink)" }}
                onClick={() => updateSelected({ shape: "circle" })}>Circle</button>
            </div>
          </div>
        </>
      )}

      {/* IMAGE properties */}
      {selected.type === "image" && (
        <>
          <div className="inspector-section">
            <div className="inspector-label">Image</div>
            <button className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }} onClick={onPickAsset}>
              <Icons.Image size={14} /> Replace image
            </button>
            <div style={{ marginTop: 10, fontSize: 12, color: "var(--ink-3)" }}>
              Current: <strong style={{ color: "var(--ink-2)" }}>
                {PLACEHOLDER_LIBRARY.find(p => p.id === selected.src)?.label
                  || (typeof selected.src === "string" ? decodeURIComponent(selected.src.split("/").pop().split("?")[0]) : "Custom image")}
              </strong>
            </div>
          </div>
          <div className="inspector-section">
            <div className="inspector-label">Corner radius</div>
            <NumberInput
              value={selected.borderRadius || 0}
              min={0} max={999} step={4}
              onChange={(v) => updateSelected({ borderRadius: v })}
            />
          </div>
        </>
      )}

      {/* Position / size */}
      <div className="inspector-section">
        <div className="inspector-label">Position & size</div>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 8 }}>
          <NumberInput label="X" value={Math.round(selected.x)} onChange={(v) => updateSelected({ x: v })} step={4} />
          <NumberInput label="Y" value={Math.round(selected.y)} onChange={(v) => updateSelected({ y: v })} step={4} />
          <NumberInput label="W" value={Math.round(selected.w)} onChange={(v) => updateSelected({ w: v })} step={4} />
          <NumberInput label="H" value={Math.round(selected.h)} onChange={(v) => updateSelected({ h: v })} step={4} />
        </div>
      </div>

      <div className="inspector-section">
        <div className="inspector-label">Rotation</div>
        <NumberInput value={selected.rotation || 0} min={-180} max={180} step={1} onChange={(v) => updateSelected({ rotation: v })} />
      </div>
    </div>
  );
}

// =============================================================
// Helpers: color picker, number input, asset picker
// =============================================================
// Holographic foil fill — a CSS background value usable anywhere el.fill is
// applied (shape/sticker/badge). It's the brand's single expressive note.
const HOLO_FILL = "url('assets/holo-texture.png') center/cover";

function ColorPicker({ value, onChange, allowHolo }) {
  return (
    <div>
      <div className="swatch-row" style={{ marginBottom: 10 }}>
        {BRAND_SWATCHES.map((c) => (
          <button
            key={c}
            className={`swatch ${value?.toUpperCase() === c.toUpperCase() ? "active" : ""}`}
            style={{ background: c }}
            onClick={() => onChange(c)}
          />
        ))}
        {allowHolo && (
          <button
            title="Holographic foil"
            className={`swatch ${value === HOLO_FILL ? "active" : ""}`}
            style={{ backgroundImage: "url(assets/holo-texture.png)", backgroundSize: "cover", backgroundPosition: "center" }}
            onClick={() => onChange(HOLO_FILL)}
          />
        )}
      </div>
      <div className="cp-row">
        <input
          type="color"
          value={value || "#000000"}
          onChange={(e) => onChange(e.target.value.toUpperCase())}
          className="cp-native"
        />
        <input
          className="cp-input"
          value={value || ""}
          onChange={(e) => onChange(e.target.value)}
        />
      </div>
    </div>
  );
}

function NumberInput({ value, onChange, min = -9999, max = 9999, step = 1, label }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
      {label && <span style={{ fontSize: 11, color: "var(--ink-3)", width: 14, flexShrink: 0 }}>{label}</span>}
      <div className="number-input" style={{ flex: 1, minWidth: 0 }}>
        <button onClick={() => onChange(Math.max(min, value - step))}>−</button>
        <input
          type="number"
          value={value}
          onChange={(e) => {
            const v = parseFloat(e.target.value);
            if (!isNaN(v)) onChange(Math.max(min, Math.min(max, v)));
          }}
          style={{ flex: 1, width: "auto", minWidth: 0 }}
        />
        <button onClick={() => onChange(Math.min(max, value + step))}>+</button>
      </div>
    </div>
  );
}

function AssetPickerModal({ onPick, onUpload, onClose }) {
  const fileRef = useRef(null);
  const [uploading, setUploading] = useState(false);
  const [history, setHistory] = useState(null); // null = loading/unavailable
  useEffect(() => {
    let alive = true;
    API.listUploads()
      .then(({ uploads }) => {
        if (alive) setHistory((uploads || []).filter((u) => u.isImage));
      })
      .catch(() => { if (alive) setHistory([]); }); // e.g. not signed in — just hide the section
    return () => { alive = false; };
  }, []);
  const handleFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setUploading(true);
    try { await onUpload(file); } finally { setUploading(false); }
  };
  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        background: "rgba(15,15,15,0.6)",
        display: "grid",
        placeItems: "center",
        zIndex: 200,
      }}
      onClick={onClose}
    >
      <div
        style={{
          background: "var(--surface-2)",
          color: "var(--ink)",
          borderRadius: 20,
          padding: 28,
          width: 560,
          maxHeight: "80vh",
          overflow: "auto",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600 }}>Replace image</div>
            <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 2 }}>From the Flexxi brand library</div>
          </div>
          <button className="btn btn-sm btn-ghost" onClick={onClose}><Icons.X size={14} /></button>
        </div>
        {history && history.length > 0 && (
          <>
            <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", marginBottom: 10 }}>
              Your uploads
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 22 }}>
              {history.map((u) => (
                <div
                  key={u.id}
                  onClick={() => onPick({ id: u.url, fit: "cover" })}
                  className="asset-thumb"
                  style={{ borderRadius: 12, cursor: "pointer", overflow: "hidden", border: "1.5px solid var(--line)" }}
                >
                  <div style={{ aspectRatio: "1", position: "relative", background: "var(--bg)" }}>
                    <img src={u.url} alt={u.original} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
          {PLACEHOLDER_LIBRARY.map((p) => (
            <div
              key={p.id}
              onClick={() => onPick(p)}
              className="asset-thumb"
              style={{ borderRadius: 12, cursor: "pointer", overflow: "hidden", border: "1.5px solid var(--line)" }}
            >
              <div style={{ aspectRatio: "1", position: "relative" }}>
                <PlaceholderVisual id={p.id} />
              </div>
              <div style={{ padding: "8px 10px", fontSize: 12, color: "var(--ink-2)", background: "var(--surface)" }}>
                {p.label}
              </div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 18, padding: 14, background: "var(--bg)", border: "1px dashed var(--line-2)", borderRadius: 12, textAlign: "center" }}>
          <div style={{ fontSize: 13, color: "var(--ink-2)", marginBottom: 8 }}>Or upload your own</div>
          <button className="btn btn-sm btn-surface" onClick={() => fileRef.current && fileRef.current.click()} disabled={uploading}>
            {uploading ? <span className="spinner" style={{ width: 13, height: 13 }} /> : <Icons.Upload size={13} />} Upload image
          </button>
          <input ref={fileRef} type="file" accept="image/*" style={{ display: "none" }} onChange={handleFile} />
        </div>
      </div>
    </div>
  );
}

window.ProjectRightPanel = ProjectRightPanel;
window.AssetPickerModal = AssetPickerModal;
