/* ============================================================
 * controls.jsx — Left-rail control panels
 * ============================================================ */

function Panel({ ord, title, en, children }) {
  return (
    <div className="panel">
      <div className="panel-head">
        <span className="ord">{ord}</span>
        <span className="title">{title}</span>
        <span className="en">{en}</span>
      </div>
      {children}
    </div>
  );
}

function Field({ label, value, children }) {
  return (
    <div className="field">
      {label && (
        <div className="field-label">
          <span>{label}</span>
          {value !== undefined && <span className="val">{value}</span>}
        </div>
      )}
      {children}
    </div>
  );
}

// --- Text input ---
function TextPanel({ state, set }) {
  return (
    <Panel ord="一" title="文字" en="Text">
      <Field label="正文">
        <textarea
          className="textarea"
          value={state.text}
          onChange={(e) => set({ text: e.target.value })}
          placeholder="例：未来可期、福"
          rows={2}
          style={{ fontFamily: 'var(--serif)', fontSize: 18 }}
        />
      </Field>
      <Field label="排版">
        <div className="opt-grid cols-2">
          <button
            className={`opt ${state.vertical ? "active" : ""}`}
            onClick={() => set({ vertical: true })}
          >竖排</button>
          <button
            className={`opt ${!state.vertical ? "active" : ""}`}
            onClick={() => set({ vertical: false })}
          >横排</button>
        </div>
      </Field>
      <Field label="字号" value={`${Math.round(state.fontScale * 100)}%`}>
        <input
          type="range" min="0.4" max="1.6" step="0.05"
          value={state.fontScale}
          onChange={(e) => set({ fontScale: parseFloat(e.target.value) })}
          className="slider"
        />
      </Field>
    </Panel>
  );
}

// --- Font picker ---
function FontPanel({ state, set }) {
  return (
    <Panel ord="二" title="字体" en="Calligraphy">
      <Field>
        <div className="opt-grid">
          {FONTS.map(f => (
            <button
              key={f.id}
              className={`opt ${state.fontId === f.id ? "active" : ""}`}
              onClick={() => set({ fontId: f.id })}
              style={{ fontFamily: f.family, fontWeight: f.weight, fontSize: 18, padding: "10px 4px" }}
              title={f.name}
            >
              {f.name[0]}
              <span className="sub" style={{ fontFamily: 'var(--serif)' }}>{f.name}</span>
            </button>
          ))}
        </div>
      </Field>
      <Field label="墨色">
        <div className="swatch-grid" style={{ gridTemplateColumns: "repeat(8, 1fr)" }}>
          {[
            { id: null, c: null, name: "默认" },
            { id: "ink", c: "#1a1612" },
            { id: "deep", c: "#3a322b" },
            { id: "dan", c: "#9c2f25" },
            { id: "gold", c: "#b08a3e" },
            { id: "celadon", c: "#4a6b5e" },
            { id: "indigo", c: "#34465a" },
            { id: "white", c: "#f5efe4" },
          ].map((c, i) => (
            <button
              key={i}
              className={`swatch ${(state.inkOverride || null) === c.c ? "active" : ""}`}
              onClick={() => set({ inkOverride: c.c })}
              style={{
                background: c.c || "repeating-linear-gradient(45deg, #ddd 0 4px, #fff 4px 8px)",
              }}
              title={c.name || c.c}
            />
          ))}
        </div>
      </Field>
    </Panel>
  );
}

// --- Paper panel ---
function PaperPanel({ state, set }) {
  return (
    <Panel ord="三" title="纸张" en="Paper">
      <Field label="颜色">
        <div className="swatch-grid">
          {PAPER_COLORS.map(p => (
            <button
              key={p.id}
              className={`swatch ${state.paperId === p.id ? "active" : ""}`}
              style={{ background: p.bg }}
              onClick={() => set({ paperId: p.id })}
              title={p.name}
            />
          ))}
        </div>
      </Field>
      <Field label="纹理">
        <div className="opt-grid cols-4">
          {PAPER_TEXTURES.map(t => (
            <button
              key={t.id}
              className={`opt ${state.textureId === t.id ? "active" : ""}`}
              onClick={() => set({ textureId: t.id })}
            >{t.name}</button>
          ))}
        </div>
      </Field>
    </Panel>
  );
}

// --- Shape panel ---
function ShapePanel({ state, set }) {
  return (
    <Panel ord="四" title="形状" en="Shape">
      <div className="shape-grid">
        {Object.entries(SHAPES).map(([id, def]) => (
          <button
            key={id}
            className={`shape-cell ${state.shape === id ? "active" : ""}`}
            onClick={() => {
              // when changing shape, also flip vertical to match default
              set({ shape: id, vertical: def.defaultVertical });
            }}
            title={def.name}
          >
            <ShapeIcon kind={id}/>
          </button>
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "space-around", marginTop: 8 }}>
        {Object.keys(SHAPES).map(id => (
          <span key={id} style={{
            fontSize: 9, letterSpacing: "0.12em", color: state.shape === id ? "var(--ink)" : "var(--ink-faint)",
            width: 25, textAlign: "center", display: state.shape === id ? "inline-block" : "none"
          }}>
            {SHAPES[id].name}
          </span>
        ))}
      </div>
    </Panel>
  );
}

// --- Decorations panel ---
function DecoPanel({ state, set }) {
  return (
    <Panel ord="五" title="装饰" en="Decoration">
      <Field>
        <label className={`toggle ${state.showSeal ? "on" : ""}`} onClick={() => set({ showSeal: !state.showSeal })}>
          <span className="dot"/>
          <span>朱红印章</span>
        </label>
      </Field>
      {state.showSeal && (
        <>
          <Field label="印文">
            <input
              className="input"
              value={state.sealText}
              onChange={(e) => set({ sealText: e.target.value.slice(0, 2) })}
              maxLength={2}
              style={{ fontFamily: 'var(--serif)', fontSize: 14 }}
            />
          </Field>
          <Field label="位置">
            <div className="opt-grid cols-4">
              {[
                { id: "top", name: "上" },
                { id: "bottom", name: "下" },
                { id: "tl", name: "左上" },
                { id: "br", name: "右下" },
              ].map(p => (
                <button
                  key={p.id}
                  className={`opt ${state.sealPosition === p.id ? "active" : ""}`}
                  onClick={() => set({ sealPosition: p.id })}
                >{p.name}</button>
              ))}
            </div>
          </Field>
          <Field>
            <label className={`toggle ${state.sealRound ? "on" : ""}`} onClick={() => set({ sealRound: !state.sealRound })}>
              <span className="dot"/>
              <span>圆形印章</span>
            </label>
          </Field>
        </>
      )}
      <div className="hr"/>
      <Field>
        <label className={`toggle ${state.showBorder ? "on" : ""}`} onClick={() => set({ showBorder: !state.showBorder })}>
          <span className="dot"/>
          <span>边框暗纹</span>
        </label>
      </Field>
      {state.showBorder && (
        <Field label="样式">
          <div className="opt-grid cols-2">
            <button
              className={`opt ${state.borderStyle === "single" ? "active" : ""}`}
              onClick={() => set({ borderStyle: "single" })}
            >单线</button>
            <button
              className={`opt ${state.borderStyle === "double" ? "active" : ""}`}
              onClick={() => set({ borderStyle: "double" })}
            >双线</button>
          </div>
        </Field>
      )}
      <Field>
        <label className={`toggle ${state.showGoldFleck ? "on" : ""}`} onClick={() => set({ showGoldFleck: !state.showGoldFleck })}>
          <span className="dot"/>
          <span>洒金箔</span>
        </label>
      </Field>
    </Panel>
  );
}

// --- Light/shadow panel ---
function LightPanel({ state, set }) {
  return (
    <Panel ord="六" title="光影" en="Light">
      <Field label="阴影">
        <div className="opt-grid">
          {[
            { id: "none", name: "无" },
            { id: "soft", name: "柔和" },
            { id: "hard", name: "深邃" },
          ].map(s => (
            <button
              key={s.id}
              className={`opt ${state.shadow === s.id ? "active" : ""}`}
              onClick={() => set({ shadow: s.id })}
            >{s.name}</button>
          ))}
        </div>
      </Field>
      <Field label="纸张磨损">
        <label className={`toggle ${state.paperWear ? "on" : ""}`} onClick={() => set({ paperWear: !state.paperWear })}>
          <span className="dot"/>
          <span>做旧效果</span>
        </label>
      </Field>
      <Field label="倾斜" value={`${state.rotate}°`}>
        <input
          type="range" min="-15" max="15" step="1"
          value={state.rotate}
          onChange={(e) => set({ rotate: parseInt(e.target.value) })}
          className="slider"
        />
      </Field>
    </Panel>
  );
}

// --- Mount/background panel ---
function MountPanel({ state, set }) {
  return (
    <Panel ord="七" title="装裱" en="Mounting">
      <div className="opt-grid cols-2">
        {MOUNTS.map(m => (
          <button
            key={m.id}
            className={`opt ${state.mount === m.id ? "active" : ""}`}
            onClick={() => set({ mount: m.id })}
          >{m.name}</button>
        ))}
      </div>
    </Panel>
  );
}

Object.assign(window, {
  Panel, Field,
  TextPanel, FontPanel, PaperPanel, ShapePanel, DecoPanel, LightPanel, MountPanel,
});
