/* Shared option controls used by the editor */
const { PS_DATA: D } = window;
const { useState: useStateC } = React;

/* ---- Section wrapper ---- */
function Section({ title, hint, children, style }) {
  return (
    <div style={{ marginBottom: 26, ...style }}>
      {title && (
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 13 }}>
          <span className="eyebrow">{title}</span>
          {hint && <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{hint}</span>}
        </div>
      )}
      {children}
    </div>
  );
}

/* ---- Template chooser ---- */
function TemplateGrid({ design, onPick, cols = 3, tileW = 96 }) {
  const custom = (window.PS_TPL ? window.PS_TPL.loadTemplates() : []).filter(t => t.status === "live");
  const all = [...custom, ...D.TEMPLATES];
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 12 }}>
      {all.map(t => {
        const active = design.templateId === t.id;
        const previewDesign = t.custom
          ? window.PS_TPL.applyCustom(design, t)
          : { ...D.applyTemplate(design, t), photo: t.kind === "photo" ? design.photo : null };
        return (
          <button key={t.id} className={"tile" + (active ? " is-active" : "")} onClick={() => onPick(t)}
            style={{ padding: 7, background: "var(--paper-2)", border: "1.5px solid " + (active ? "var(--clay)" : "var(--line)"), display: "flex", flexDirection: "column", gap: 7, alignItems: "center", position: "relative" }}>
            <div style={{ width: "100%", aspectRatio: ".75", borderRadius: 5, overflow: "hidden", boxShadow: "var(--sh-sm)" }}>
              <div style={{ width: "100%", height: "100%" }}><PosterArt d={previewDesign} /></div>
            </div>
            <span style={{ fontSize: 11.5, fontWeight: 600, color: active ? "var(--clay-dark)" : "var(--ink-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: "100%" }}>{t.name}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ---- Text fields ---- */
function TextFields({ design, update }) {
  const fieldStyle = { width: "100%", padding: "11px 13px", border: "1.5px solid var(--line-2)", borderRadius: "var(--r-sm)", background: "var(--card)", color: "var(--ink)", fontSize: 14.5, outline: "none", resize: "none" };
  const fz = e => e.target.style.borderColor = "var(--clay)";
  const bz = e => e.target.style.borderColor = "var(--line-2)";

  // custom template: one input per locked text zone
  if (design.custom && design.zones) {
    const textZones = design.zones.filter(z => z.type !== "photo");
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {textZones.map((z, i) => {
          const len = (z.text || "").length;
          const over = z.maxLen && len > z.maxLen;
          return (
            <label key={z.id} style={{ display: "block" }}>
              <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                <span>Text {i + 1}</span>
                {z.maxLen ? <span style={{ color: over ? "var(--clay-dark)" : "var(--ink-3)", fontWeight: 600 }}>{len}/{z.maxLen}</span> : null}
              </span>
              <textarea value={z.text} rows={(z.text || "").length > 22 ? 2 : 1}
                onChange={e => { let v = e.target.value; if (z.maxLen) v = v.slice(0, z.maxLen); update({ zones: design.zones.map(x => x.id === z.id ? { ...x, text: v } : x) }); }}
                style={fieldStyle} onFocus={fz} onBlur={bz} />
            </label>
          );
        })}
        <div style={{ display: "flex", gap: 8, alignItems: "center", padding: "9px 12px", background: "var(--paper-2)", borderRadius: "var(--r-sm)", color: "var(--ink-3)", fontSize: 12 }}>
          <Icon name="Lock" size={13} /> Fonts &amp; layout are set by this template.
        </div>
      </div>
    );
  }

  const t = D.TEMPLATES.find(x => x.id === design.templateId);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <label style={{ display: "block" }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", display: "block", marginBottom: 6 }}>Headline</span>
        <textarea value={design.headline} rows={2} onChange={e => update({ headline: e.target.value })} style={fieldStyle}
          onFocus={fz} onBlur={bz} />
      </label>
      <label style={{ display: "block" }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", display: "block", marginBottom: 6 }}>Subline</span>
        <input value={design.subline} onChange={e => update({ subline: e.target.value })} style={fieldStyle}
          onFocus={e => e.target.style.borderColor = "var(--clay)"} onBlur={e => e.target.style.borderColor = "var(--line-2)"} />
      </label>
      {(t && (t.kind === "name" || t.kind === "coords")) && (
        <label style={{ display: "block" }}>
          <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", display: "block", marginBottom: 6 }}>{t.kind === "coords" ? "Coordinates" : "Names"}</span>
          <input value={design.meta} onChange={e => update({ meta: e.target.value })} style={fieldStyle}
            onFocus={e => e.target.style.borderColor = "var(--clay)"} onBlur={e => e.target.style.borderColor = "var(--line-2)"} />
        </label>
      )}
    </div>
  );
}

/* ---- Font row ---- */
function FontRow({ design, update }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 9 }}>
      {D.POSTER_FONTS.map(f => {
        const active = design.font === f.id;
        return (
          <button key={f.id} className={"tile" + (active ? " is-active" : "")} onClick={() => update({ font: f.id })}
            style={{ padding: "10px 4px 8px", display: "flex", flexDirection: "column", alignItems: "center", gap: 3, border: "1.5px solid " + (active ? "var(--clay)" : "var(--line)") }}>
            <span style={{ fontFamily: f.css, fontSize: 26, lineHeight: 1, color: "var(--ink)", fontWeight: f.weight }}>{f.sample}</span>
            <span style={{ fontSize: 10.5, fontWeight: 600, color: active ? "var(--clay-dark)" : "var(--ink-3)" }}>{f.label}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ---- generic swatch row ---- */
function SwatchRow({ items, value, onPick, getHex, getLabel }) {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 12 }}>
      {items.map(it => {
        const id = it.id !== undefined ? it.id : it;
        const hex = getHex(it);
        const active = value === id;
        return (
          <button key={id} title={getLabel ? getLabel(it) : ""} onClick={() => onPick(id)}
            className={"swatch" + (active ? " is-active" : "")}
            style={{ width: 38, height: 38, background: hex }}>
            {active && <Icon name="Check" size={16} style={{ position: "absolute", inset: 0, margin: "auto", color: tone(hex) }} />}
          </button>
        );
      })}
    </div>
  );
}
function tone(hex) {
  const c = hex.replace("#", ""); if (c.length < 6) return "#fff";
  const r = parseInt(c.slice(0,2),16), g = parseInt(c.slice(2,4),16), b = parseInt(c.slice(4,6),16);
  return (r*299 + g*587 + b*114) / 1000 > 150 ? "#3A2D20" : "#FFF7EF";
}

function BgRow({ design, update }) {
  return <SwatchRow items={D.BG_COLORS} value={design.bg} onPick={id => {
    const c = D.BG_COLORS.find(x => x.id === id);
    update({ bg: id, textColor: c ? c.ink : design.textColor });
  }} getHex={it => it.hex} getLabel={it => it.label} />;
}
function TextColorRow({ design, update }) {
  return <SwatchRow items={D.TEXT_COLORS} value={design.textColor} onPick={id => update({ textColor: id })} getHex={it => it} />;
}

/* ---- Size picker ---- */
function SizeRow({ design, update, dir = "row", lock }) {
  if (lock) {
    const s = D.SIZES.find(x => x.id === design.size) || D.SIZES[1];
    return <LockedRow icon="Ruler" label={s.label + " cm"} sub={s.sub + " · set by your order"} />;
  }
  return (
    <div style={{ display: dir === "row" ? "grid" : "flex", gridTemplateColumns: "repeat(2,1fr)", flexDirection: dir === "col" ? "column" : undefined, gap: 10 }}>
      {D.SIZES.map(s => {
        const active = design.size === s.id;
        return (
          <button key={s.id} className={"tile" + (active ? " is-active" : "")} onClick={() => update({ size: s.id })}
            style={{ padding: "12px 14px", display: "flex", alignItems: "center", gap: 12, border: "1.5px solid " + (active ? "var(--clay)" : "var(--line)"), textAlign: "left" }}>
            <span style={{ width: 26 * s.ratio + 8, minWidth: 16, height: 30, border: "2px solid " + (active ? "var(--clay)" : "var(--line-strong)"), borderRadius: 3, flex: "none", background: "var(--paper-2)" }} />
            <span style={{ display: "flex", flexDirection: "column" }}>
              <span style={{ fontWeight: 700, fontSize: 14.5, color: "var(--ink)" }}>{s.label} <span style={{ fontWeight: 500, fontSize: 11.5, color: "var(--ink-3)" }}>cm</span></span>
              <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{s.sub}{s.add ? ` · +$${s.add}` : " · included"}</span>
            </span>
          </button>
        );
      })}
    </div>
  );
}

/* Locked option row (Etsy: size/frame already chosen at purchase) */
function LockedRow({ icon, label, sub }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 15px", background: "var(--paper-2)", border: "1.5px solid var(--line)", borderRadius: "var(--r-md)" }}>
      <Icon name={icon} size={19} style={{ color: "var(--ink-3)", flex: "none" }} />
      <span style={{ display: "flex", flexDirection: "column", flex: 1 }}>
        <span style={{ fontWeight: 700, fontSize: 14, color: "var(--ink)" }}>{label}</span>
        <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{sub}</span>
      </span>
      <Icon name="Lock" size={15} style={{ color: "var(--ink-3)" }} />
    </div>
  );
}

/* ---- Frame picker ---- */
function FrameRow({ design, update, lock }) {
  if (lock) {
    const f = D.FRAMES.find(x => x.id === design.frame) || D.FRAMES[0];
    return <LockedRow icon="Frame" label={f.label + " frame"} sub="set by your order" />;
  }
  return (
    <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
      {D.FRAMES.map(f => {
        const active = design.frame === f.id;
        return (
          <button key={f.id} onClick={() => update({ frame: f.id })}
            style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 7, background: "none", border: "none", padding: 0, cursor: "pointer" }}>
            <span style={{
              width: 46, height: 46, borderRadius: 9, background: f.id === "none" ? "var(--paper-2)" : f.thumb,
              border: f.id === "none" ? "1.5px dashed var(--line-strong)" : "1px solid rgba(0,0,0,.12)",
              boxShadow: active ? "0 0 0 2px var(--paper), 0 0 0 4px var(--clay)" : "var(--sh-sm)",
              display: "flex", alignItems: "center", justifyContent: "center", transition: "box-shadow .15s",
            }}>
              {f.id === "none" && <Icon name="Ban" size={18} style={{ color: "var(--ink-3)" }} />}
              {f.id !== "none" && <span style={{ width: 22, height: 22, background: "#FCF9F1", borderRadius: 2, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.08)" }} />}
            </span>
            <span style={{ fontSize: 11.5, fontWeight: 600, color: active ? "var(--clay-dark)" : "var(--ink-3)" }}>{f.label}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ---- Price + CTA bar ---- */
function PriceBar({ design, compact, onAdd }) {
  const price = D.priceFor(design);
  const size = D.SIZES.find(s => s.id === design.size);
  const frame = D.FRAMES.find(f => f.id === design.frame);
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, width: "100%" }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
          <span style={{ fontFamily: "var(--serif)", fontSize: 26, fontWeight: 600, color: "var(--ink)" }}>${price}</span>
          {!compact && <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{size.label} cm · {frame.label}</span>}
        </div>
        {!compact && <span style={{ fontSize: 11.5, color: "var(--sage)", fontWeight: 600, display: "flex", alignItems: "center", gap: 5 }}><Icon name="Truck" size={13} /> Free shipping over $150</span>}
      </div>
      <button className="btn btn-primary" style={{ flex: compact ? 1 : "none", maxWidth: compact ? 220 : undefined }} onClick={onAdd}>
        <Icon name="ShoppingBag" size={18} /> Add to cart
      </button>
    </div>
  );
}

Object.assign(window, {
  Section, TemplateGrid, TextFields,
  FontRow, BgRow, TextColorRow, SizeRow, FrameRow, PriceBar, SwatchRow, LockedRow,
});
