// placeholder.jsx — shared small UI pieces.
// Exports to window: Slot, Chip, Wordmark

// A drag-and-drop image placeholder the user fills later. Wraps <image-slot>.
// `id` MUST be globally unique and stable so the dropped image persists.
function Slot({ id, label, radius = 0, fit = "cover", style }) {
  return (
    <image-slot
      id={id}
      placeholder={label}
      shape="rounded"
      radius={String(radius)}
      fit={fit}
      style={{ width: "100%", height: "100%", ...style }}
    ></image-slot>
  );
}

// Full-bleed background image layer + its controls. Invisible until an image
// is dropped (empty-state chrome hidden via CSS), so a section with no
// background looks unchanged. A readability scrim ("반투명") sits over the
// image and can be toggled off ("선명") per background. The scrim preference
// persists per slot id in localStorage. Controls show only in editable mode.
// `id` MUST be globally unique & stable.
function Background({ id }) {
  const editable = typeof window !== "undefined" && window.omelette && window.omelette.writeFile;
  const [filled, setFilled] = React.useState(false);
  const [scrim, setScrim] = React.useState(() => {
    try { return localStorage.getItem(`pf-scrim:${id}`) !== "off"; } catch (e) { return true; }
  });

  React.useEffect(() => {
    const el = document.getElementById(id);
    if (!el) return;
    const sync = () => setFilled(el.hasAttribute("data-filled"));
    sync();
    const obs = new MutationObserver(sync);
    obs.observe(el, { attributes: true, attributeFilter: ["data-filled"] });
    return () => obs.disconnect();
  }, [id]);

  const pick = () => {
    const el = document.getElementById(id);
    const input = el && el.shadowRoot && el.shadowRoot.querySelector('input[type="file"]');
    if (input) input.click();
  };
  const toggleScrim = () => {
    setScrim((s) => {
      const next = !s;
      try { localStorage.setItem(`pf-scrim:${id}`, next ? "on" : "off"); } catch (e) {}
      return next;
    });
  };

  return (
    <React.Fragment>
      <div className={"pf-bg" + (scrim ? "" : " pf-bg--clear")}>
        <Slot id={id} label="배경 이미지 (선택 · 권장 2400×1350)" radius={0} />
      </div>
      {editable && (
        <div className="pf-bgctl">
          <button className="pf-bgbtn" onClick={pick}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="8.5" cy="8.5" r="1.5" /><path d="m21 15-5-5L5 21" />
            </svg>
            {filled ? "배경 변경" : "배경 추가"}
          </button>
          {filled && (
            <button className="pf-bgbtn pf-bgbtn--scrim" data-on={scrim ? "1" : "0"} onClick={toggleScrim}
              title="배경 위 반투명 오버레이를 켜고 끕니다">
              <span className="pf-bgbtn__dot"></span>
              {scrim ? "반투명" : "선명"}
            </button>
          )}
        </div>
      )}
    </React.Fragment>
  );
}

// Small monospace-ish meta chip for tools / disciplines.
function Chip({ children, subtle }) {
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        height: 28,
        padding: "0 12px",
        borderRadius: 999,
        fontSize: 13,
        lineHeight: 1,
        fontWeight: 500,
        letterSpacing: "0.01em",
        color: subtle ? "var(--text-2)" : "var(--text)",
        background: subtle ? "transparent" : "var(--surface)",
        border: subtle ? "1px solid var(--border)" : "1px solid transparent",
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </span>
  );
}

// Brand wordmark used in the header.
function Wordmark({ onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "flex-start",
        gap: 1,
        lineHeight: 1.05,
        textAlign: "left",
      }}
      aria-label="홈으로"
    >
      <span style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-0.01em" }}>
        방명환
      </span>
      <span style={{ fontSize: 11.5, fontWeight: 500, letterSpacing: "0.16em", color: "var(--text-3)", textTransform: "uppercase" }}>
        Change &amp; Adapt
      </span>
    </button>
  );
}

Object.assign(window, { Slot, Chip, Wordmark, Background });
