// ==========================================================================
// Components / Layout 家族 — thumbnails + detail pages
// ==========================================================================
const { Demo: __Demo_la, DocCard: __DocCard_la, Bar: __Bar_la, FieldLabel: __FieldLabel_la, tfStyle: __tfStyle_la } = window;
const Demo = __Demo_la, DocCard = __DocCard_la, Bar = __Bar_la, FieldLabel = __FieldLabel_la, tfStyle = __tfStyle_la;

const T_Form = () => (
  <div style={{ width: 160, padding: 8, background: "#fff", border: "1px solid var(--blue-500)", borderRadius: 4, display: "flex", flexDirection: "column", gap: 6 }}>
    {[0, 1, 2].map(i =>
      <div key={i} style={{ height: 16, border: "1px solid var(--n-300)", borderRadius: 3, padding: "0 6px", display: "flex", alignItems: "center" }}>
        <Bar w="60%" h={3} c="var(--n-300)" />
      </div>
    )}
    <div style={{ alignSelf: "flex-end", width: 40, height: 14, background: "var(--blue-500)", borderRadius: 2 }} />
  </div>
);
const T_Scrollbar = () => (
  <div style={{ width: 130, height: 76, background: "#fff", border: "1px solid var(--n-300)", borderRadius: 4, position: "relative", padding: 6, display: "flex", flexDirection: "column", gap: 4 }}>
    {[0, 1, 2, 3].map(i => <Bar key={i} w="80%" h={3} c="var(--n-300)" />)}
    <div style={{ position: "absolute", top: 6, right: 4, width: 4, height: 32, background: "var(--blue-500)", borderRadius: 999 }} />
  </div>
);
const T_ImageList = () => (
  <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 3, width: 110 }}>
    {[0, 1, 2, 3, 4, 5].map(i =>
      <div key={i} style={{ aspectRatio: "1", background: ["var(--blue-100)", "var(--blue-200)", "var(--blue-300)", "var(--blue-200)", "var(--blue-100)", "var(--blue-300)"][i], borderRadius: 2 }} />
    )}
  </div>
);
const T_Splitter = () => (
  <div style={{ display: "flex", width: 160, height: 70, border: "1px solid var(--n-300)", borderRadius: 4, overflow: "hidden" }}>
    <div style={{ width: "40%", background: "var(--blue-50)" }} />
    <div style={{ width: 6, background: "var(--blue-500)", cursor: "ew-resize", position: "relative" }}>
      <div style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%,-50%)", width: 2, height: 16, background: "#fff", borderRadius: 1 }} />
    </div>
    <div style={{ flex: 1, background: "var(--n-50)" }} />
  </div>
);
const T_Masonry = () => (
  <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 30px)", gap: 4, alignItems: "flex-start" }}>
    {[26, 38, 22, 32, 28, 36, 20, 30, 26].map((h, i) =>
      <div key={i} style={{ width: 30, height: h, background: ["var(--blue-100)", "var(--blue-200)", "var(--blue-300)"][i % 3], borderRadius: 3 }} />
    )}
  </div>
);

// ---------- Detail Cards ----------
const DocLayout = () => (
  <>
    <DocCard id="c-layout-form" en="Form" intro="表單是使用者與系統的主要對話通道。建議 label 在欄位上方、必填欄位用 *、錯誤訊息緊貼欄位下方。">
      <Demo title="基本表單" fitContent><FormDemo /></Demo>
      <Demo title="水平排列" fitContent><FormHorizontal /></Demo>
    </DocCard>

    <DocCard id="c-layout-scrollbar" en="Scrollbar guidelines" intro="預設使用瀏覽器原生捲軸；客製化捲軸用於 sidebar、Modal 等空間有限的容器。寬度建議 6-8px。">
      <Demo title="客製化捲軸" fitContent>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, width: "100%" }}>
          {[
            { l: "細捲軸 (6px)", w: 6 },
            { l: "標準 (8px)", w: 8 },
          ].map(s => (
            <div key={s.l}>
              <div className="ds-cap" style={{ marginBottom: 6 }}>{s.l}</div>
              <div className="ds-scroll-demo" style={{ "--sw": `${s.w}px` }}>
                {Array.from({ length: 12 }).map((_, i) => (
                  <div key={i} style={{ padding: "8px 12px", fontSize: 13, color: "var(--n-700)", borderBottom: "1px solid var(--n-100)" }}>清單項目 {i + 1}</div>
                ))}
              </div>
            </div>
          ))}
        </div>
        <style>{`
          .ds-scroll-demo{height:160px;overflow-y:auto;background:#fff;border:1px solid var(--n-200);border-radius:6px}
          .ds-scroll-demo::-webkit-scrollbar{width:var(--sw)}
          .ds-scroll-demo::-webkit-scrollbar-track{background:transparent}
          .ds-scroll-demo::-webkit-scrollbar-thumb{background:var(--n-300);border-radius:999px}
          .ds-scroll-demo::-webkit-scrollbar-thumb:hover{background:var(--blue-500)}
        `}</style>
      </Demo>
    </DocCard>

    <DocCard id="c-layout-imagelist" en="Image List" intro="圖片網格列表，常用於相簿、商品縮圖、設計作品集。所有圖片同尺寸 (1:1 / 16:9)。">
      <Demo title="基本網格">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, width: "100%" }}>
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} style={{ aspectRatio: "1", borderRadius: 8, background: `linear-gradient(135deg, var(--blue-${[100, 200, 300, 400][i % 4]}), var(--blue-${[400, 500, 600, 700][i % 4]}))`, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--ff-en)", fontSize: 18, fontWeight: 600 }}>{i + 1}</div>
          ))}
        </div>
      </Demo>
      <Demo title="附標題">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, width: "100%" }}>
          {[
            { t: "城市夜景", a: "Photographer A" },
            { t: "山林晨霧", a: "Photographer B" },
            { t: "海岸線", a: "Photographer C" },
          ].map((p, i) => (
            <div key={i} style={{ borderRadius: 8, overflow: "hidden", background: "#fff", border: "1px solid var(--n-200)" }}>
              <div style={{ aspectRatio: "4/3", background: `linear-gradient(135deg, var(--blue-${[300, 400, 200][i]}), var(--blue-${[600, 700, 500][i]}))` }} />
              <div style={{ padding: 10 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{p.t}</div>
                <div className="ds-cap">{p.a}</div>
              </div>
            </div>
          ))}
        </div>
      </Demo>
    </DocCard>

    <DocCard id="c-layout-splitter" en="Splitter" intro="分割器讓使用者可拖曳調整兩個區域的寬度，常用於 IDE、檔案管理、雙欄編輯器。">
      <Demo title="水平分割" fitContent><SplitterDemo direction="h" /></Demo>
      <Demo title="垂直分割" fitContent><SplitterDemo direction="v" /></Demo>
    </DocCard>

    <DocCard id="c-layout-masonry" en="Masonry" intro="瀑布流佈局，項目高度不一時仍能緊密排列，常見於圖片牆、Pinterest 風格頁面。">
      <Demo title="基本用法">
        <div style={{ columnCount: 4, columnGap: 10, width: "100%" }}>
          {[180, 120, 220, 160, 100, 200, 140, 240, 180, 130, 200, 160].map((h, i) => (
            <div key={i} style={{ height: h, breakInside: "avoid", marginBottom: 10, borderRadius: 8, background: `linear-gradient(135deg, var(--blue-${[100, 200, 300][i % 3]}), var(--blue-${[400, 500, 600][i % 3]}))`, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--ff-en)", fontWeight: 600 }}>{i + 1}</div>
          ))}
        </div>
      </Demo>
    </DocCard>
  </>
);

// ---------- demo helpers ----------
const FormDemo = () => (
  <div style={{ width: "100%", maxWidth: 480 }}>
    <h4 style={{ margin: "0 0 4px", fontSize: 16, fontWeight: 600 }}>建立新專案</h4>
    <p className="ds-cap" style={{ marginBottom: 18 }}>標示 * 為必填欄位</p>
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div>
        <FieldLabel>專案名稱 *</FieldLabel>
        <input style={tfStyle()} defaultValue="2026 春季活動" />
      </div>
      <div>
        <FieldLabel>描述</FieldLabel>
        <textarea style={{ ...tfStyle(), height: 70, padding: 10, resize: "vertical" }} placeholder="專案目標與內容…" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <div>
          <FieldLabel>類型 *</FieldLabel>
          <Select options={["行銷活動", "產品設計", "內部專案"]} defaultIndex={0} width="100%" />
        </div>
        <div>
          <FieldLabel>截止日期</FieldLabel>
          <input type="date" style={tfStyle()} defaultValue="2026-06-30" />
        </div>
      </div>
      <div>
        <FieldLabel>權限</FieldLabel>
        <RadioGroup options={["僅自己可見", "團隊可見", "公開連結"]} defaultIndex={0} />
      </div>
    </div>
    <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 24, paddingTop: 18, borderTop: "1px solid var(--n-200)" }}>
      <B kind="outline">取消</B>
      <B kind="filled">建立專案</B>
    </div>
  </div>
);

const FormHorizontal = () => (
  <div style={{ width: "100%", maxWidth: 560 }}>
    {[
      { l: "姓名", v: "林小明", t: "text" },
      { l: "Email", v: "ming@example.com", t: "email" },
      { l: "電話", v: "0912-345-678", t: "tel" },
    ].map(f => (
      <div key={f.l} style={{ display: "grid", gridTemplateColumns: "100px 1fr", alignItems: "center", gap: 12, marginBottom: 12 }}>
        <FieldLabel>{f.l}</FieldLabel>
        <input type={f.t} defaultValue={f.v} style={tfStyle()} />
      </div>
    ))}
    <div style={{ display: "grid", gridTemplateColumns: "100px 1fr", gap: 12, alignItems: "center" }}>
      <FieldLabel>啟用通知</FieldLabel>
      <Switch defaultOn />
    </div>
    <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 18 }}>
      <B kind="filled">儲存</B>
    </div>
  </div>
);

const SplitterDemo = ({ direction = "h" }) => {
  const [pct, setPct] = React.useState(40);
  const ref = React.useRef(null);
  const dragging = React.useRef(false);
  React.useEffect(() => {
    const onMove = (e) => {
      if (!dragging.current || !ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const p = direction === "h"
        ? ((e.clientX - r.left) / r.width) * 100
        : ((e.clientY - r.top) / r.height) * 100;
      setPct(Math.max(15, Math.min(85, p)));
    };
    const onUp = () => { dragging.current = false; document.body.style.cursor = ""; };
    document.addEventListener("mousemove", onMove);
    document.addEventListener("mouseup", onUp);
    return () => { document.removeEventListener("mousemove", onMove); document.removeEventListener("mouseup", onUp); };
  }, [direction]);
  const isH = direction === "h";
  return (
    <div ref={ref} style={{ display: "flex", flexDirection: isH ? "row" : "column", width: "100%", height: 240, border: "1px solid var(--n-200)", borderRadius: 8, overflow: "hidden", background: "#fff", userSelect: "none" }}>
      <div style={{ [isH ? "width" : "height"]: `${pct}%`, background: "var(--blue-50)", padding: 16, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--blue-700)", fontSize: 13 }}>
        側欄 ({Math.round(pct)}%)
      </div>
      <div onMouseDown={() => { dragging.current = true; document.body.style.cursor = isH ? "ew-resize" : "ns-resize"; }}
        style={{
          [isH ? "width" : "height"]: 6,
          [isH ? "minWidth" : "minHeight"]: 6,
          background: "var(--n-200)",
          cursor: isH ? "ew-resize" : "ns-resize",
          display: "flex", alignItems: "center", justifyContent: "center",
          position: "relative",
          transition: "background var(--dur-fast) var(--ease)",
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = "var(--blue-500)"}
        onMouseLeave={(e) => e.currentTarget.style.background = "var(--n-200)"}>
        <div style={{ [isH ? "height" : "width"]: 20, [isH ? "width" : "height"]: 2, background: "#fff", borderRadius: 1 }} />
      </div>
      <div style={{ flex: 1, background: "var(--n-50)", padding: 16, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--n-700)", fontSize: 13 }}>
        主內容區
      </div>
    </div>
  );
};

Object.assign(window, { T_Form, T_Scrollbar, T_ImageList, T_Splitter, T_Masonry, DocLayout });
