// ─── K&N Elite — Shared components (light theme unified) ───

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// Unsplash luxury real estate photos — stable IDs
const PHOTOS = {
  hero: "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=2000&q=80&auto=format&fit=crop",
  apt1: "https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?w=1200&q=80&auto=format&fit=crop",
  apt2: "https://images.unsplash.com/photo-1560518883-ce09059eeffa?w=1200&q=80&auto=format&fit=crop",
  apt3: "https://images.unsplash.com/photo-1600566753190-17f0baa2a6c3?w=1200&q=80&auto=format&fit=crop",
  apt4: "https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?w=1200&q=80&auto=format&fit=crop",
  apt5: "https://images.unsplash.com/photo-1600607687644-c7171b42498f?w=1200&q=80&auto=format&fit=crop",
  apt6: "https://images.unsplash.com/photo-1613977257363-707ba9348227?w=1200&q=80&auto=format&fit=crop",
  interior1: "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?w=1200&q=80&auto=format&fit=crop",
  interior2: "https://images.unsplash.com/photo-1600566753051-6057e2f04f83?w=1200&q=80&auto=format&fit=crop",
  interior3: "https://images.unsplash.com/photo-1616594039964-ae9021a400a0?w=1200&q=80&auto=format&fit=crop",
  interior4: "https://images.unsplash.com/photo-1600585154526-990dced4db0d?w=1200&q=80&auto=format&fit=crop",
};
window.PHOTOS = PHOTOS;

// ─── Logo mark (real PNG — gold key in circle) ───
function BrandMark({ size = 40 }) {
  return (
    <img
      src="assets/logo-mark.png"
      alt="K&N Elite"
      className="brand-mark-img"
      style={{ width: size, height: size, display: "block" }}
    />
  );
}

// Full logo as image (for hero use where needed)
function BrandFull({ height = 64, variant = "dark" }) {
  // dark = original (white text + gold key, for dark bg)
  // light = inverted text (dark text + gold key, for light bg)
  const filter = variant === "light"
    ? "invert(0.85) hue-rotate(0deg) brightness(0.75) saturate(1.2)"
    : "none";
  return (
    <img
      src="assets/logo-full.png"
      alt="K&N Elite Real Estate Agency"
      style={{ height, width: "auto", display: "block", filter }}
    />
  );
}

function Brand({ onClick, floating = false, compact = false }) {
  const { t } = useI18n();
  return (
    <div className="brand" onClick={onClick} role="button" tabIndex={0}>
      <BrandMark size={compact ? 42 : 52} />
      <div style={{ lineHeight: 1 }}>
        <div className="brand-text">
          K<span className="amp">&amp;</span>N&nbsp;ELITE
        </div>
        {!compact && <span className="brand-sub">{t("brand_sub")}</span>}
      </div>
    </div>
  );
}

// ─── Language switcher ───
function LangSwitch() {
  const { lang, setLang } = useI18n();
  return (
    <div className="lang-switch">
      {["es", "en", "ru"].map((l) => (
        <button key={l} className={lang === l ? "active" : ""} onClick={() => setLang(l)}>
          {l.toUpperCase()}
        </button>
      ))}
    </div>
  );
}

// ─── Topbar ───
function Topbar({ onNav, current, floating = false }) {
  const { t } = useI18n();
  return (
    <header className={"topbar" + (floating ? " topbar-floating" : "")}>
      <Brand onClick={() => onNav("home")} />
      <nav className="nav">
        <a className={current === "home" ? "active" : ""} onClick={() => onNav("home")}>{t("nav_funnel")}</a>
        <a className={current === "cabinet" ? "active" : ""} onClick={() => onNav("cabinet")}>{t("nav_cabinet")}</a>
        <a className={current === "admin" ? "active" : ""} onClick={() => onNav("admin")}>{t("nav_admin")}</a>
        <LangSwitch />
      </nav>
    </header>
  );
}

// ─── Footer ───
function Footer() {
  const { t } = useI18n();
  return (
    <footer style={{
      borderTop: "1px solid var(--ink-10)",
      padding: "36px 48px",
      display: "flex", justifyContent: "space-between", alignItems: "center",
      flexWrap: "wrap", gap: "20px",
      fontSize: "12px",
      color: "var(--ink-60)",
      letterSpacing: "0.02em",
      marginTop: 80,
    }}>
      <div>{t("footer_rights")}</div>
      <div style={{ display: "flex", gap: "28px" }}>
        <a style={{ color: "inherit", textDecoration: "none", cursor: "pointer" }}>{t("privacy")}</a>
        <a style={{ color: "inherit", textDecoration: "none", cursor: "pointer" }}>{t("terms")}</a>
        <a style={{ color: "inherit", textDecoration: "none", cursor: "pointer" }}>{t("legal")}</a>
      </div>
    </footer>
  );
}

// ─── Toast ───
function useToast() {
  const [msg, setMsg] = useState(null);
  const show = useCallback((m) => {
    setMsg(m);
    setTimeout(() => setMsg(null), 2600);
  }, []);
  const node = msg ? <div className="toast show"><span className="ok">✓</span> {msg}</div> : null;
  return { showToast: show, toastNode: node };
}

// ─── CountUp hook (animated number) ───
function useCountUp(target, duration = 1800, fmt = (v) => Math.round(v).toLocaleString("es-ES").replace(/,/g, " ")) {
  const [value, setValue] = useState(0);
  const startRef = useRef(null);
  const targetRef = useRef(target);
  useEffect(() => {
    targetRef.current = target;
    let raf;
    startRef.current = performance.now();
    const startVal = 0;
    const tick = (now) => {
      const p = Math.min(1, (now - startRef.current) / duration);
      const eased = 1 - Math.pow(1 - p, 4);
      setValue(startVal + (targetRef.current - startVal) * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);
  return fmt(value);
}

// ─── Progress bar (under topbar) ───
function ProgressBar({ step, total = 3 }) {
  const pct = total === 0 ? 0 : ((step + 1) / total) * 100;
  return (
    <div className="progress-bar">
      <div className="progress-bar-fill" style={{ width: pct + "%" }} />
    </div>
  );
}

// ─── Big step header (HUGE number + meta) ───
function StepHeader({ step, total = 3, labels }) {
  const num = String(step + 1).padStart(2, "0");
  return (
    <div className="step-header rise">
      <div className="step-big-num active">{num}</div>
      <div className="step-meta">
        <div className="eyebrow">Step {num} / {String(total).padStart(2, "0")}</div>
        <h1 style={{ fontSize: "clamp(32px, 3.6vw, 52px)", marginTop: 4 }}>{labels[step]}</h1>
      </div>
    </div>
  );
}

// ─── Horizontal stepper (compact) ───
function StepperH({ step, labels }) {
  return (
    <div className="stepper-h">
      {labels.map((lab, i) => (
        <div key={i} className={"step " + (i === step ? "active" : i < step ? "done" : "")}>
          <div className="step-dot">0{i + 1}</div>
          <div className="step-lbl">{lab}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Checkbox ───
function Checkbox({ checked, onChange, children, required = false }) {
  return (
    <label style={{
      display: "flex", alignItems: "flex-start", gap: 12,
      cursor: "pointer", userSelect: "none",
      fontSize: 13, lineHeight: 1.6, color: "var(--ink-soft)",
    }}>
      <span
        onClick={(e) => { e.preventDefault(); onChange(!checked); }}
        style={{
          width: 20, height: 20, minWidth: 20,
          border: `1px solid ${checked ? "var(--gold-deep)" : "var(--ink-20)"}`,
          background: checked ? "var(--gold)" : "var(--paper)",
          borderRadius: 2,
          display: "inline-grid", placeItems: "center",
          marginTop: 1,
          transition: "all .25s var(--ease)",
        }}>
        {checked && (
          <svg width="12" height="12" viewBox="0 0 11 11" fill="none">
            <path d="M2 5.5 L4.5 8 L9 2.5" stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        )}
      </span>
      <span>{children}{required && <span style={{ color: "var(--err)" }}> *</span>}</span>
    </label>
  );
}

// ─── Segmented toggle ───
function SegmentedToggle({ options, value, onChange }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: `repeat(${options.length}, 1fr)`,
      border: "1px solid var(--ink-10)",
      borderRadius: 2,
      overflow: "hidden",
      background: "var(--paper)",
    }}>
      {options.map((o) => (
        <button key={o.value} onClick={() => onChange(o.value)}
          style={{
            padding: "16px 14px",
            background: value === o.value ? "var(--ink)" : "transparent",
            color: value === o.value ? "var(--ivory)" : "var(--ink)",
            border: "none",
            fontFamily: "var(--sans)",
            fontSize: 13, fontWeight: 500, letterSpacing: "0.03em",
            cursor: "pointer",
            transition: "all .3s var(--ease)",
            minHeight: 56,
          }}>{o.label}</button>
      ))}
    </div>
  );
}

// ─── Chip multi-select ───
function ChipMulti({ options, values, onToggle }) {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
      {options.map((o) => {
        const active = values.includes(o.value);
        return (
          <button key={o.value} onClick={() => onToggle(o.value)}
            style={{
              border: `1px solid ${active ? "var(--gold)" : "var(--ink-10)"}`,
              background: active ? "var(--gold-10)" : "var(--paper)",
              color: active ? "var(--gold-deep)" : "var(--ink)",
              padding: "12px 18px",
              borderRadius: 100,
              fontSize: 13, fontFamily: "var(--sans)",
              cursor: "pointer",
              transition: "all .25s var(--ease)",
              minHeight: 44,
              fontWeight: active ? 500 : 400,
            }}>
            {active && <span style={{ marginRight: 6, color: "var(--gold-deep)" }}>✓</span>}
            {o.label}
          </button>
        );
      })}
    </div>
  );
}

function fmt(n) { return Math.round(n).toLocaleString("es-ES").replace(/,/g, " "); }

function Ornament() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, color: "var(--gold)", fontSize: 12 }}>
      <span style={{ flex: 1, height: 1, background: "var(--gold-20)" }} />
      <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 18 }}>✦</span>
      <span style={{ flex: 1, height: 1, background: "var(--gold-20)" }} />
    </div>
  );
}

Object.assign(window, {
  BrandMark, BrandFull, Brand, LangSwitch, Topbar, Footer,
  useToast, useCountUp, ProgressBar, StepHeader, StepperH,
  Checkbox, SegmentedToggle, ChipMulti, Ornament, fmt,
});
