// Reusable UI parts
const { useState, useEffect, useRef } = React;

function Nav({ lang, setLang, content, onContact }) {
  const [active, setActive] = useState("hero");
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => {
      const ids = content.nav.map(n => n.id);
      for (const id of ids) {
        const el = document.getElementById(id);
        if (!el) continue;
        const r = el.getBoundingClientRect();
        if (r.top <= 120 && r.bottom >= 120) { setActive(id); break; }
      }
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [content]);

  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  const go = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 64, behavior: "smooth" });
    setMenuOpen(false);
  };

  return (
    <>
      <nav className="nav">
        <div className="nav-row">
          <a href="#hero" onClick={go("hero")} className="brand">
            <img src="images/site/logo.png" alt="AVK Aydın Vinç Kiralama" style={{ height: "40px", maxWidth: "200px", width: "auto", display: "block", objectFit: "contain" }} />
          </a>
          <div className="nav-links">
            {content.nav.map(n => (
              <a key={n.id} href={"#" + n.id} onClick={go(n.id)} className={"nav-link " + (active === n.id ? "active" : "")}>{n.label}</a>
            ))}
          </div>
          <div className="nav-cta">
            <div className="phone-pill">
              <span className="dot"></span>
              0312 395 58 62
            </div>
            {setLang && (
              <div className="nav-lang">
                <button className={lang === "tr" ? "on" : ""} onClick={() => setLang("tr")}>TR</button>
                <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
              </div>
            )}
            <button className="btn btn-primary" onClick={onContact}>{lang === "tr" ? "Teklif Al" : "Get Quote"}</button>
            <button className="nav-hamburger" onClick={() => setMenuOpen(true)} aria-label="Menü">
              <span/><span/><span/>
            </button>
          </div>
        </div>
      </nav>

      <div className={"mobile-menu " + (menuOpen ? "open" : "")} role="dialog" aria-modal="true">
        <button className="mobile-menu-close" onClick={() => setMenuOpen(false)}>✕</button>
        {content.nav.map(n => (
          <a key={n.id} href={"#" + n.id} onClick={go(n.id)} className="mobile-nav-link">{n.label}</a>
        ))}
        <div className="mobile-menu-foot">
          <button className="btn btn-primary btn-arrow" onClick={() => { onContact(); setMenuOpen(false); }}>
            {lang === "tr" ? "Teklif Al" : "Get Quote"}
          </button>
          <a href="tel:+903123955862" className="btn btn-ghost">
            0312 395 58 62
          </a>
          {setLang && (
            <div className="nav-lang" style={{ alignSelf: "flex-start", marginTop: 4 }}>
              <button className={lang === "tr" ? "on" : ""} onClick={() => setLang("tr")}>TR</button>
              <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

function Ticker({ items }) {
  const doubled = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {doubled.map((t, i) => <span key={i}>◇ <b>{t}</b></span>)}
      </div>
    </div>
  );
}

function WAFab({ lang }) {
  return (
    <a className="wa-fab" href="https://wa.me/903123955862" target="_blank" rel="noopener">
      <svg viewBox="0 0 24 24" fill="currentColor">
        <path d="M20.5 3.5A11 11 0 0 0 3.5 17.5L2 22l4.7-1.4a11 11 0 0 0 13.8-17.1zM12 20a8 8 0 0 1-4.1-1.1l-.3-.2-2.8.8.8-2.7-.2-.3A8 8 0 1 1 12 20zm4.4-5.8c-.2-.1-1.4-.7-1.6-.8s-.4-.1-.5.1-.6.8-.8 1c-.1.1-.3.1-.5 0a6.5 6.5 0 0 1-3.2-2.8c-.2-.4.2-.3.6-1 .1-.1 0-.3 0-.4l-.7-1.7c-.2-.4-.4-.4-.5-.4h-.5a1 1 0 0 0-.7.3 3 3 0 0 0-.9 2.2c0 1.3 1 2.6 1.1 2.7s1.9 2.9 4.6 4a10 10 0 0 0 1.6.5c.7.2 1.3.2 1.8.1.5-.1 1.4-.6 1.6-1.2s.2-1 .1-1.2-.2-.1-.4-.2z"/>
      </svg>
      <div className="wa-label">
        <b>WhatsApp</b>
        <small>{lang === "tr" ? "Hızlı yazış" : "Quick chat"}</small>
      </div>
    </a>
  );
}

function ContactModal({ open, onClose, info, lang }) {
  return (
    <div className={"modal-backdrop " + (open ? "open" : "")} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h3>{lang === "tr" ? "İletişim" : "Contact"}</h3>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div className="modal-row">
            <div className="icon">☎</div>
            <div>
              <div className="lbl">{lang === "tr" ? "Telefon (7/24)" : "Phone (24/7)"}</div>
              <a href={"tel:" + info.phone.replace(/\s/g,"")} className="val">{info.phone}</a>
            </div>
          </div>
          <div className="modal-row">
            <div className="icon">@</div>
            <div>
              <div className="lbl">E-mail</div>
              <a href={"mailto:" + info.email} className="val">{info.email}</a>
            </div>
          </div>
          <div className="modal-row">
            <div className="icon">◉</div>
            <div>
              <div className="lbl">{lang === "tr" ? "Adres" : "Address"}</div>
              <div className="val sm" style={{ whiteSpace: "pre-line" }}>{info.address}</div>
            </div>
          </div>
          <div className="modal-row">
            <div className="icon">◐</div>
            <div>
              <div className="lbl">{lang === "tr" ? "Çalışma Saatleri" : "Hours"}</div>
              <div className="val sm">{info.hours}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function TweaksPanel({ open, setOpen, tweaks, setTweaks }) {
  if (!open) return null;
  const colors = [
    { key: "#facc15", name: "Sarı" },
    { key: "#f97316", name: "Turuncu" },
    { key: "#ef4444", name: "Kırmızı" },
    { key: "#22d3ee", name: "Siyan" },
    { key: "#a3e635", name: "Yeşil" },
  ];
  const set = (patch) => {
    const next = { ...tweaks, ...patch };
    setTweaks(next);
    try {
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: patch }, "*");
    } catch (e) {}
  };
  return (
    <div className={"tweaks " + (open ? "open" : "")}>
      <div className="tweaks-head">
        <b>Tweaks</b>
        <button className="x" onClick={() => setOpen(false)}>kapat</button>
      </div>
      <div className="tweak-row">
        <div className="t-label">Vurgu rengi</div>
        <div className="color-dots">
          {colors.map(c => (
            <div key={c.key} className={"color-dot " + (tweaks.accent === c.key ? "on" : "")}
              style={{ background: c.key }} title={c.name}
              onClick={() => set({ accent: c.key })} />
          ))}
        </div>
      </div>
      <div className="tweak-row">
        <div className="t-label">Tema</div>
        <div className="seg">
          <button className={tweaks.theme === "dark" ? "on" : ""} onClick={() => set({ theme: "dark" })}>Koyu</button>
          <button className={tweaks.theme === "light" ? "on" : ""} onClick={() => set({ theme: "light" })}>Açık</button>
        </div>
      </div>
      <div className="tweak-row">
        <div className="t-label">Dil</div>
        <div className="seg">
          <button className={tweaks.lang === "tr" ? "on" : ""} onClick={() => set({ lang: "tr" })}>TR</button>
          <button className={tweaks.lang === "en" ? "on" : ""} onClick={() => set({ lang: "en" })}>EN</button>
        </div>
      </div>
      <div className="tweak-row">
        <div className="t-label">Ticker</div>
        <div className="seg">
          <button className={tweaks.showTicker ? "on" : ""} onClick={() => set({ showTicker: true })}>Açık</button>
          <button className={!tweaks.showTicker ? "on" : ""} onClick={() => set({ showTicker: false })}>Kapalı</button>
        </div>
      </div>
    </div>
  );
}

function MapCanvas({ filter, hovered, setHovered, selected, setSelected }) {
  const hq = GEO.hq;
  const showAnkara = filter === "all" || filter === "ankara";
  const showProv = filter === "all" || filter === "provinces" || (filter !== "ankara" && filter !== "all");
  const activeProv = filter !== "all" && filter !== "ankara" && filter !== "provinces" ? filter : null;

  const isDimmed = (kind, key) => {
    if (filter === "all") return false;
    if (filter === "ankara") return kind !== "ankara";
    if (filter === "provinces") return kind !== "province";
    return !(kind === "province" && key === filter);
  };

  return (
    <svg viewBox="0 0 100 75" className="map-canvas" preserveAspectRatio="xMidYMid meet">
      <defs>
        <pattern id="mapgrid" width="5" height="5" patternUnits="userSpaceOnUse">
          <path d="M 5 0 L 0 0 0 5" fill="none" stroke="var(--line)" strokeWidth="0.15"/>
        </pattern>
        <pattern id="mapgridFine" width="1" height="1" patternUnits="userSpaceOnUse">
          <path d="M 1 0 L 0 0 0 1" fill="none" stroke="var(--line)" strokeWidth="0.05" opacity="0.5"/>
        </pattern>
        <radialGradient id="hqGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.25"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
        </radialGradient>
      </defs>
      <rect width="100" height="75" fill="url(#mapgridFine)"/>
      <rect width="100" height="75" fill="url(#mapgrid)"/>

      {/* Crosshair through HQ */}
      <line x1="0" y1={hq.y} x2="100" y2={hq.y} stroke="var(--accent)" strokeWidth="0.08" strokeDasharray="0.5 1.2" opacity="0.35"/>
      <line x1={hq.x} y1="0" x2={hq.x} y2="75" stroke="var(--accent)" strokeWidth="0.08" strokeDasharray="0.5 1.2" opacity="0.35"/>

      {/* Delivery radius rings with labels */}
      {[
        { r: 6, label: "4 SAAT" },
        { r: 14, label: "250 KM" },
        { r: 24, label: "500 KM" },
      ].map((ring, i) => (
        <g key={i}>
          <circle cx={hq.x} cy={hq.y} r={ring.r} fill="none" stroke="var(--accent)" strokeWidth="0.12" strokeDasharray="0.6 0.8" opacity={0.25 + i * 0.1}/>
          <text x={hq.x + ring.r - 0.5} y={hq.y - 0.5} fontSize="1.4" fill="var(--fg-3)" fontFamily="var(--font-mono)" textAnchor="end" style={{letterSpacing: "0.08em"}}>{ring.label}</text>
        </g>
      ))}

      {/* HQ radial glow */}
      <circle cx={hq.x} cy={hq.y} r="10" fill="url(#hqGlow)"/>

      {/* Province connections from HQ */}
      {GEO.provinces.map((p, i) => {
        const dim = isDimmed("province", p.key);
        return (
          <line key={i} x1={hq.x} y1={hq.y} x2={p.hub.x} y2={p.hub.y}
            stroke={activeProv === p.key ? "var(--accent)" : "var(--line-2)"}
            strokeWidth={activeProv === p.key ? "0.3" : "0.18"}
            strokeDasharray="1 1" opacity={dim ? 0.15 : 0.7}/>
        );
      })}

      {/* Ankara districts — small markers */}
      {showAnkara && GEO.ankara.map((d, i) => {
        const isHover = hovered && hovered.kind === "ankara" && hovered.idx === i;
        const isSel = selected && selected.kind === "ankara" && selected.idx === i;
        const r = d.zone === 1 ? 0.7 : 0.55;
        return (
          <g key={"a" + i}
             onMouseEnter={() => setHovered({ kind: "ankara", idx: i, data: d })}
             onMouseLeave={() => setHovered(null)}
             onClick={() => setSelected({ kind: "ankara", idx: i, data: d })}
             style={{ cursor: "pointer" }}>
            {(isHover || isSel) && (
              <circle cx={d.x} cy={d.y} r="2.8" fill="none" stroke="var(--accent)" strokeWidth="0.25" opacity="0.7"/>
            )}
            {(isHover || isSel) && (
              <circle cx={d.x} cy={d.y} r="1.4" fill="var(--accent)" opacity="0.25"/>
            )}
            <circle cx={d.x} cy={d.y} r={r}
              fill={isSel ? "var(--accent)" : d.zone === 1 ? "var(--accent)" : "var(--fg)"}
              opacity={isDimmed("ankara", null) ? 0.2 : 1}/>
          </g>
        );
      })}

      {/* Province hubs and towns */}
      {showProv && GEO.provinces.map((p, i) => {
        const dim = isDimmed("province", p.key);
        const isActive = activeProv === p.key;
        return (
          <g key={"p" + i} opacity={dim ? 0.2 : 1}>
            {/* cluster zone */}
            {isActive && (
              <circle cx={p.hub.x} cy={p.hub.y} r="5.5" fill="var(--accent)" opacity="0.06" stroke="var(--accent)" strokeWidth="0.1" strokeDasharray="0.3 0.5"/>
            )}
            {/* towns */}
            {p.towns.filter(t => !t.hub).map((t, ti) => {
              const isHover = hovered && hovered.kind === "town" && hovered.provKey === p.key && hovered.idx === ti;
              return (
                <g key={ti}
                   onMouseEnter={() => setHovered({ kind: "town", provKey: p.key, idx: ti, data: { ...t, province: p.name } })}
                   onMouseLeave={() => setHovered(null)}
                   onClick={() => setSelected({ kind: "town", provKey: p.key, idx: ti, data: { ...t, province: p.name } })}
                   style={{ cursor: "pointer" }}>
                  {isHover && <circle cx={t.x} cy={t.y} r="1.6" fill="none" stroke="var(--accent)" strokeWidth="0.15"/>}
                  <circle cx={t.x} cy={t.y} r="0.45" fill="var(--fg-2)"/>
                  {isHover && (
                    <g>
                      <rect x={t.x + 1.2} y={t.y - 2.6} width={t.name.length * 1.1 + 2.5} height="3.2" fill="var(--bg)" stroke="var(--accent)" strokeWidth="0.12"/>
                      <text x={t.x + 2.4} y={t.y - 0.4} fontSize="1.8" fill="var(--fg)" fontFamily="var(--font-mono)" style={{letterSpacing: "0.04em"}}>{t.name.toUpperCase()}</text>
                    </g>
                  )}
                </g>
              );
            })}
            {/* hub marker */}
            {(() => {
              const isProvHover = hovered && hovered.kind === "province" && hovered.provKey === p.key;
              const showLabel = isActive || isProvHover;
              return (
                <g onMouseEnter={() => setHovered({ kind: "province", provKey: p.key, data: p })}
                   onMouseLeave={() => setHovered(null)}
                   onClick={() => setSelected({ kind: "province", provKey: p.key, data: p })}
                   style={{ cursor: "pointer" }}>
                  <circle cx={p.hub.x} cy={p.hub.y} r="1.6" fill={showLabel ? "var(--accent)" : "var(--fg)"}/>
                  <circle cx={p.hub.x} cy={p.hub.y} r="2.6" fill="none" stroke={showLabel ? "var(--accent)" : "var(--fg-2)"} strokeWidth="0.18"/>
                  {showLabel ? (
                    <g>
                      <rect x={p.hub.x - p.name.length * 1.1 - 1} y={p.hub.y + 3.2} width={p.name.length * 2.2 + 2} height="3.2" fill="var(--bg)" stroke="var(--accent)" strokeWidth="0.1"/>
                      <text x={p.hub.x} y={p.hub.y + 5.6} fontSize="2.2" fill="var(--accent)"
                            fontFamily="var(--font-display)" fontWeight="600" textAnchor="middle" style={{letterSpacing: "0.06em"}}>{p.name}</text>
                    </g>
                  ) : (
                    <text x={p.hub.x} y={p.hub.y - 3} fontSize="1.6" fill="var(--fg-2)"
                          fontFamily="var(--font-mono)" textAnchor="middle" style={{letterSpacing: "0.06em"}}>{p.name.slice(0,3)}</text>
                  )}
                </g>
              );
            })()}
          </g>
        );
      })}

      {/* HQ marker — always on top */}
      <g>
        <circle cx={hq.x} cy={hq.y} r="2.8" fill="none" stroke="var(--accent)" strokeWidth="0.25"/>
        <circle cx={hq.x} cy={hq.y} r="1.8" fill="var(--accent)"/>
        <circle cx={hq.x} cy={hq.y} r="0.6" fill="var(--accent-ink)"/>
        <text x={hq.x + 3.5} y={hq.y + 0.5} fontSize="1.7" fill="var(--accent)" fontFamily="var(--font-mono)" fontWeight="500" style={{letterSpacing: "0.1em"}}>HQ</text>
      </g>
    </svg>
  );
}

function MobileBar({ lang }) {
  return (
    <div className="mobile-bar">
      <a href="https://wa.me/903123955862" target="_blank" rel="noopener" className="mobile-bar-btn mobile-bar-wp">
        <svg viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
          <path d="M20.5 3.5A11 11 0 0 0 3.5 17.5L2 22l4.7-1.4a11 11 0 0 0 13.8-17.1zM12 20a8 8 0 0 1-4.1-1.1l-.3-.2-2.8.8.8-2.7-.2-.3A8 8 0 1 1 12 20zm4.4-5.8c-.2-.1-1.4-.7-1.6-.8s-.4-.1-.5.1-.6.8-.8 1c-.1.1-.3.1-.5 0a6.5 6.5 0 0 1-3.2-2.8c-.2-.4.2-.3.6-1 .1-.1 0-.3 0-.4l-.7-1.7c-.2-.4-.4-.4-.5-.4h-.5a1 1 0 0 0-.7.3 3 3 0 0 0-.9 2.2c0 1.3 1 2.6 1.1 2.7s1.9 2.9 4.6 4a10 10 0 0 0 1.6.5c.7.2 1.3.2 1.8.1.5-.1 1.4-.6 1.6-1.2s.2-1 .1-1.2-.2-.1-.4-.2z"/>
        </svg>
        WhatsApp
      </a>
      <a href="tel:+903123955862" className="mobile-bar-btn mobile-bar-phone">
        <svg viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
          <path d="M6.6 10.8c1.4 2.8 3.8 5.1 6.6 6.6l2.2-2.2c.3-.3.7-.4 1-.2 1.1.4 2.3.6 3.6.6.6 0 1 .4 1 1V20c0 .6-.4 1-1 1-9.4 0-17-7.6-17-17 0-.6.4-1 1-1h3.5c.6 0 1 .4 1 1 0 1.3.2 2.5.6 3.6.1.3 0 .7-.2 1L6.6 10.8z"/>
        </svg>
        {lang === "tr" ? "Hemen Ara" : "Call Now"}
      </a>
    </div>
  );
}

Object.assign(window, { Nav, Ticker, WAFab, MobileBar, ContactModal, TweaksPanel, MapCanvas });
