/* ============================================================
   Shared UI primitives + icons
   Exposed on window for cross-file use.
   ============================================================ */
const { useState, useEffect, useRef, useCallback } = React;

/* ---------- Icons (simple, consistent stroke) ---------- */
const Ic = {
  shield: (p) => (<svg width={p?.s||20} height={p?.s||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2.5l7 2.8v5.2c0 4.6-3 8.4-7 9.5-4-1.1-7-4.9-7-9.5V5.3l7-2.8z"/><path d="M9 12l2 2 4-4"/></svg>),
  lock: (p) => (<svg width={p?.s||20} height={p?.s||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4.5" y="10.5" width="15" height="10" rx="2.5"/><path d="M8 10.5V7a4 4 0 018 0v3.5"/><circle cx="12" cy="15.5" r="1.4" fill="currentColor" stroke="none"/></svg>),
  check: (p) => (<svg width={p?.s||16} height={p?.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 6.5"/></svg>),
  copy: (p) => (<svg width={p?.s||15} height={p?.s||15} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="8.5" y="8.5" width="11" height="11" rx="2.5"/><path d="M5.5 15.5H5a1.5 1.5 0 01-1.5-1.5V5A1.5 1.5 0 015 3.5h9A1.5 1.5 0 0115.5 5v.5"/></svg>),
  arrow: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h13M13 6l6 6-6 6"/></svg>),
  back: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H6M11 6l-6 6 6 6"/></svg>),
  chevron: (p) => (<svg width={p?.s||16} height={p?.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6"/></svg>),
  download: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3.5v11M7.5 10l4.5 4.5 4.5-4.5M4.5 19.5h15"/></svg>),
  mail: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2.5"/><path d="M4 7l8 6 8-6"/></svg>),
  bell: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8a6 6 0 10-12 0c0 7-2.5 8-2.5 8h17S18 15 18 8z"/><path d="M10.5 20.5a2 2 0 003 0"/></svg>),
  globe: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18"/></svg>),
  file: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2.5h7l5 5v14a0 0 0 010 0H6a0 0 0 010 0V2.5z" transform="translate(0 0)"/><path d="M13 2.5V8h5"/></svg>),
  clock: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3.5 2"/></svg>),
  plus: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14"/></svg>),
  search: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></svg>),
  refresh: (p) => (<svg width={p?.s||16} height={p?.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 11a8 8 0 10-1.5 5.5M20 4.5V11h-6.5"/></svg>),
  spinner: (p) => (<svg className="spin" width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M12 3a9 9 0 109 9" opacity=".9"/><path d="M21 12a9 9 0 00-9-9" opacity=".25"/></svg>),
  eye: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>),
  eyeoff: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3l18 18M10.6 10.6a3 3 0 004.2 4.2M9.4 5.3A9.6 9.6 0 0112 5c6.5 0 10 7 10 7a16 16 0 01-3.3 4M6.2 6.2A16 16 0 002 12s3.5 7 10 7a9.6 9.6 0 003.4-.6"/></svg>),
  zap: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2.5L4.5 13.5H11l-1 8 8.5-11H12l1-8z"/></svg>),
  layers: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l9 5-9 5-9-5 9-5z"/><path d="M3 13l9 5 9-5"/></svg>),
  logout: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 4.5H6.5A1.5 1.5 0 005 6v12a1.5 1.5 0 001.5 1.5H15M10 12h10M16 8l4 4-4 4"/></svg>),
  user: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="3.6"/><path d="M4.5 20a7.5 7.5 0 0115 0"/></svg>),
  trash: (p) => (<svg width={p?.s||16} height={p?.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 7h16M9 7V5a1 1 0 011-1h4a1 1 0 011 1v2M6 7l1 13a1 1 0 001 1h8a1 1 0 001-1l1-13"/></svg>),
  close: (p) => (<svg width={p?.s||18} height={p?.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 6l12 12M18 6L6 18"/></svg>),
};

/* ---------- Brand logo ---------- */
function Brand({ onClick }) {
  return (
    <div className="brand" onClick={onClick}>
      <div className="brand-mark">{Ic.shield({ s: 19 })}</div>
      <div className="brand-name">90 Day <span>Free SSL</span></div>
    </div>
  );
}

/* ---------- Button ---------- */
function Btn({ kind = "primary", size, block, children, icon, iconRight, ...rest }) {
  const cls = ["btn", `btn-${kind}`, size && `btn-${size}`, block && "btn-block"].filter(Boolean).join(" ");
  return (
    <button className={cls} {...rest}>
      {icon}{children}{iconRight}
    </button>
  );
}

/* ---------- Badge ---------- */
function Badge({ tone = "gray", children, dot = true }) {
  return <span className={`badge badge-${tone}`}>{dot && <span className="dot" />}{children}</span>;
}

/* ---------- Toggle ---------- */
function Toggle({ checked, onChange }) {
  return (
    <label className="switch">
      <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} />
      <span className="track" />
    </label>
  );
}

/* ---------- Checkbox row ---------- */
function Check({ checked, onChange, children }) {
  return (
    <div className={`check ${checked ? "on" : ""}`} onClick={() => onChange(!checked)}>
      <span className="box">{Ic.check({ s: 13 })}</span>
      <span style={{ fontSize: 14, color: "var(--text-2)", lineHeight: 1.45 }}>{children}</span>
    </div>
  );
}

/* ---------- Copy button ---------- */
function CopyBtn({ text, label = "Kopyala" }) {
  const [done, setDone] = useState(false);
  const copy = () => {
    try { navigator.clipboard?.writeText(text); } catch (e) {}
    setDone(true); setTimeout(() => setDone(false), 1400);
  };
  return (
    <button className={`copy-btn ${done ? "done" : ""}`} onClick={copy}>
      {done ? Ic.check({ s: 14 }) : Ic.copy({ s: 14 })}
      {done ? "Kopyalandı" : label}
    </button>
  );
}

/* ---------- Field ---------- */
function Field({ label, optional, hint, error, children }) {
  return (
    <div className={`field ${error ? "field-err" : ""}`}>
      {label && <label className="label">{label}{optional && <span className="opt"> · opsiyonel</span>}</label>}
      {children}
      {error ? <span className="hint err">{error}</span> : hint ? <span className="hint">{hint}</span> : null}
    </div>
  );
}

/* ---------- Custom Select (styled dropdown) ---------- */
// Türkçe/diakritik duyarsız normalize — "tür" → "turkiye" eşleşsin diye.
function selNorm(s) {
  return (s == null ? "" : "" + s).toLowerCase()
    .replace(/ı/g, "i").replace(/i̇/g, "i").replace(/ş/g, "s").replace(/ç/g, "c")
    .replace(/ğ/g, "g").replace(/ü/g, "u").replace(/ö/g, "o").replace(/â/g, "a").replace(/î/g, "i").replace(/û/g, "u");
}

function Select({ value, onChange, options, placeholder = "Seçiniz" }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const ref = useRef(null);
  const searchRef = useRef(null);
  const searchable = (options || []).length > 8;   // uzun listelerde ara kutusu (örn. ülkeler)

  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  useEffect(() => {
    if (open) { setQ(""); if (searchable) setTimeout(() => { try { searchRef.current && searchRef.current.focus(); } catch (e) {} }, 10); }
  }, [open]);

  const shown = (searchable && q) ? (options || []).filter(o => selNorm(o).includes(selNorm(q))) : (options || []);
  const choose = (o) => { onChange(o); setOpen(false); setQ(""); };

  return (
    <div className="sel" ref={ref}>
      <button type="button" className={`sel-btn ${open ? "open" : ""}`} onClick={() => setOpen(o => !o)}>
        <span className={value ? "" : "ph"}>{value || placeholder}</span>
        <span className="sel-chev" style={{ transform: open ? "rotate(180deg)" : "none" }}>{Ic.chevron({ s: 16 })}</span>
      </button>
      {open && (
        <div className="sel-pop">
          {searchable && (
            <div style={{ position: "sticky", top: "-6px", zIndex: 1, margin: "-6px -6px 6px", padding: "8px", background: "var(--surface)", borderBottom: "1px solid var(--border)" }}>
              <input ref={searchRef} className="input" style={{ height: 36, fontSize: 13.5 }} placeholder="Ara… (harf yazın)" value={q}
                     onChange={e => setQ(e.target.value)}
                     onKeyDown={e => { if (e.key === "Enter") { e.preventDefault(); if (shown.length) choose(shown[0]); } else if (e.key === "Escape") setOpen(false); }} />
            </div>
          )}
          {shown.map(o => (
            <button type="button" key={o} className={`sel-opt ${o === value ? "on" : ""}`}
                    onClick={() => choose(o)}>
              <span>{o}</span>
              {o === value && <span style={{ color: "var(--primary)", display: "inline-flex" }}>{Ic.check({ s: 15 })}</span>}
            </button>
          ))}
          {shown.length === 0 && <div className="hint" style={{ padding: "10px 14px", textAlign: "center" }}>Sonuç yok</div>}
        </div>
      )}
    </div>
  );
}

/* ---------- Modal ---------- */
function Modal({ open, onClose, title, sub, children, footer, width = 560 }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", h);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", h); document.body.style.overflow = ""; };
  }, [open]);
  if (!open) return null;
  return (
    <div className="modal-ov" onMouseDown={onClose}>
      <div className="modal-card" style={{ maxWidth: width }} onMouseDown={e => e.stopPropagation()}>
        <div className="modal-head">
          <div style={{ minWidth: 0 }}>
            <div className="modal-title">{title}</div>
            {sub && <div className="hint" style={{ marginTop: 3 }}>{sub}</div>}
          </div>
          <button className="modal-x" onClick={onClose} aria-label="Kapat">{Ic.close({ s: 18 })}</button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

/* ---------- AdSlot (Google AdSense) — tüm sayfalarda kullanılır ---------- */
function AdSlot({ format = "leaderboard", label, slot }) {
  const s = (typeof getSettings === "function") ? getSettings() : {};
  if (!s.adsEnabled) return null;
  const real = s.adsClient && s.adsClient.indexOf("ca-pub-") === 0 && s.adsClient !== "ca-pub-0000000000000000";
  const dims = { leaderboard: "728 × 90", rectangle: "336 × 280", infeed: "responsive" };
  useEffect(() => { if (real) { try { (window.adsbygoogle = window.adsbygoogle || []).push({}); } catch (e) {} } }, []);
  if (real) {
    return <ins className="adsbygoogle" style={{ display: "block" }} data-ad-client={s.adsClient}
                data-ad-slot={slot || ""} data-ad-format="auto" data-full-width-responsive="true" aria-label="Reklam" />;
  }
  return (
    <div className={`ad-slot ad-${format}`} data-ad-client={s.adsClient} data-ad-format={format} aria-label="Reklam">
      <span className="ad-lbl">{label || "Reklam"} · Google Ads</span>
      <span className="ad-dim">{dims[format] || ""}</span>
    </div>
  );
}

Object.assign(window, { Ic, Brand, Btn, Badge, Toggle, Check, CopyBtn, Field, Select, Modal, AdSlot,
  useState, useEffect, useRef, useCallback });
