// ─── K&N Elite — Admin (unified light) ───

const { useState } = React;

const ADMIN_REQUESTS = [
  { id: "R-1042", date: "24 Apr · 14:22", name: "María Fernández", phone: "+34 612 345 678", address: "Calle Serrano 42, Madrid", type: "valuation", status: "new", mgr: "—", lang: "ES" },
  { id: "R-1041", date: "24 Apr · 13:58", name: "Ivan Petrov", phone: "+34 698 221 044", address: "Paseo de Gracia 89, Barcelona", type: "visit", status: "in_progress", mgr: "C. Tenorio", lang: "RU" },
  { id: "R-1040", date: "24 Apr · 12:30", name: "Laura Giménez", phone: "+34 600 147 852", address: "Av. del Puerto 118, Valencia", type: "valuation", status: "in_progress", mgr: "L. Ramos", lang: "ES" },
  { id: "R-1039", date: "24 Apr · 11:04", name: "Hans Müller", phone: "+49 170 444 888", address: "Calle Mayor 7, Alicante", type: "valuation", status: "done", mgr: "A. Vidal", lang: "EN" },
  { id: "R-1038", date: "23 Apr · 19:41", name: "Olga Sokolova", phone: "+34 611 909 012", address: "Calle Velázquez 80, Madrid", type: "valuation", status: "new", mgr: "—", lang: "RU" },
  { id: "R-1037", date: "23 Apr · 17:20", name: "Thomas Lefevre", phone: "+33 633 121 212", address: "Calle Alcalá 200, Madrid", type: "out", status: "new", mgr: "—", lang: "EN" },
  { id: "R-1036", date: "23 Apr · 15:55", name: "Elena García", phone: "+34 622 334 455", address: "Calle Gran Vía 34, Madrid", type: "visit", status: "done", mgr: "C. Tenorio", lang: "ES" },
];

function AdminShell({ onNav, tab, setTab, children }) {
  const { t } = useI18n();
  return (
    <div className="page fade">
      <Topbar onNav={onNav} current="admin" />
      <div style={{ borderBottom: "1px solid var(--ink-10)", background: "var(--paper)" }}>
        <div className="container" style={{ padding: "0 48px" }}>
          <div style={{ display: "flex", alignItems: "center" }}>
            <span className="mono" style={{ color: "var(--gold-deep)", marginRight: 32, padding: "22px 0" }}>ADMIN · INTERNAL</span>
            {[
              { k: "requests",   l: t("adm_requests") },
              { k: "clients",    l: t("adm_clients") },
              { k: "properties", l: t("adm_properties") },
              { k: "analytics",  l: t("adm_analytics") },
              { k: "users",      l: t("adm_users") },
            ].map(it => (
              <button key={it.k} onClick={() => setTab(it.k)}
                style={{
                  background: "transparent", border: "none",
                  padding: "22px 22px", cursor: "pointer", fontSize: 13,
                  color: tab === it.k ? "var(--ink)" : "var(--ink-60)",
                  borderBottom: `2px solid ${tab === it.k ? "var(--gold)" : "transparent"}`,
                  marginBottom: -1, fontWeight: tab === it.k ? 500 : 400,
                  transition: "all .25s",
                }}>{it.l}</button>
            ))}
          </div>
        </div>
      </div>
      <main style={{ flex: 1, padding: "48px" }}>{children}</main>
      <Footer />
    </div>
  );
}

function AdminRequests({ onOpen }) {
  const { t } = useI18n();
  const [filter, setFilter] = useState("all");
  const [search, setSearch] = useState("");

  const filtered = ADMIN_REQUESTS.filter(r => {
    if (filter !== "all" && r.status !== filter) return false;
    if (search && !(r.name.toLowerCase().includes(search.toLowerCase()) ||
                    r.address.toLowerCase().includes(search.toLowerCase()) ||
                    r.phone.includes(search))) return false;
    return true;
  });

  const tone = { new: "var(--gold)", in_progress: "var(--warn)", done: "var(--ok)", error: "var(--err)" };
  const lbl = { new: t("adm_st_new"), in_progress: t("adm_st_prog"), done: t("adm_st_done"), error: t("adm_st_err") };
  const typeLbl = { valuation: t("adm_type_val"), visit: t("adm_type_visit"), out: t("adm_type_out") };

  return (
    <div className="container rise">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 32 }}>
        <div>
          <div className="eyebrow">01</div>
          <h1 style={{ marginTop: 12, fontSize: 44 }}>{t("adm_requests")}</h1>
        </div>
        <input className="input" placeholder={t("adm_search")}
          value={search} onChange={e => setSearch(e.target.value)}
          style={{ width: 320, minHeight: 44 }} />
      </div>

      <div style={{ display: "flex", gap: 8, marginBottom: 24, flexWrap: "wrap" }}>
        {[{ k: "all", l: t("adm_all") }, { k: "new", l: t("adm_st_new") }, { k: "in_progress", l: t("adm_st_prog") }, { k: "done", l: t("adm_st_done") }].map(f => (
          <button key={f.k} onClick={() => setFilter(f.k)}
            style={{
              background: filter === f.k ? "var(--ink)" : "var(--paper)",
              color: filter === f.k ? "var(--ivory)" : "var(--ink-60)",
              border: `1px solid ${filter === f.k ? "var(--ink)" : "var(--ink-10)"}`,
              padding: "10px 18px", fontSize: 11,
              fontFamily: "var(--mono)", letterSpacing: "0.14em", textTransform: "uppercase",
              borderRadius: 100, cursor: "pointer", transition: "all .25s",
            }}>{f.l}</button>
        ))}
      </div>

      <div style={{ background: "var(--paper)", border: "1px solid var(--ink-10)" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "130px 1fr 1.1fr 1.5fr 100px 120px 120px 50px",
          padding: "16px 24px", borderBottom: "1px solid var(--ink-10)",
          fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-60)",
        }}>
          <div>{t("adm_date")}</div><div>{t("adm_client")}</div><div>{t("adm_phone")}</div>
          <div>{t("adm_address")}</div><div>{t("adm_type")}</div><div>{t("adm_status")}</div>
          <div>{t("adm_mgr")}</div><div>{t("adm_lang")}</div>
        </div>
        {filtered.map(r => (
          <div key={r.id} onClick={() => onOpen(r)}
            style={{
              display: "grid", gridTemplateColumns: "130px 1fr 1.1fr 1.5fr 100px 120px 120px 50px",
              padding: "18px 24px", borderBottom: "1px solid var(--ink-10)",
              fontSize: 13, cursor: "pointer", alignItems: "center", transition: "all .2s",
            }}
            onMouseEnter={e => e.currentTarget.style.background = "var(--gold-10)"}
            onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
            <div className="mono" style={{ color: "var(--ink-60)" }}>{r.date}</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 16 }}>{r.name}</div>
            <div className="mono" style={{ fontSize: 12 }}>{r.phone}</div>
            <div style={{ color: "var(--ink-60)" }}>{r.address}</div>
            <div><span className="chip" style={{ fontSize: 10, padding: "3px 10px" }}>{typeLbl[r.type]}</span></div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: tone[r.status] }} />
              <span className="mono" style={{ color: tone[r.status], fontSize: 10 }}>{lbl[r.status]}</span>
            </div>
            <div style={{ color: r.mgr === "—" ? "var(--ink-40)" : "var(--ink)" }}>{r.mgr}</div>
            <div className="mono" style={{ color: "var(--gold-deep)" }}>{r.lang}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AdminRequestModal({ req, onClose }) {
  const { t } = useI18n();
  if (!req) return null;
  return (
    <div style={{
      position: "fixed", inset: 0, background: "rgba(26,23,20,0.5)", backdropFilter: "blur(4px)",
      zIndex: 200, display: "grid", placeItems: "center", animation: "fade-in .2s",
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()}
        style={{
          width: "min(880px, 94vw)", maxHeight: "90vh", overflow: "auto",
          background: "var(--paper)", animation: "scale-in .35s", borderRadius: 2,
        }}>
        <div style={{ padding: "28px 40px", borderBottom: "1px solid var(--ink-10)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div className="eyebrow">{req.id}</div>
            <h3 style={{ marginTop: 8 }}>{req.name}</h3>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", fontSize: 28, cursor: "pointer", color: "var(--ink-60)" }}>×</button>
        </div>
        <div style={{ padding: 40, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40 }}>
          <div>
            <div className="eyebrow">{t("adm_card_data")}</div>
            <div style={{ marginTop: 16, display: "grid", gap: 10, fontSize: 14 }}>
              <div><b>Phone:</b> <span className="mono">{req.phone}</span></div>
              <div><b>Address:</b> {req.address}</div>
              <div><b>Language:</b> {req.lang}</div>
              <div><b>Area:</b> 112 m² · 3 rooms · 2 baths</div>
            </div>
            <div style={{ marginTop: 32 }}>
              <div className="eyebrow">{t("adm_card_history")}</div>
              <ul style={{ listStyle: "none", marginTop: 14, display: "grid", gap: 8 }}>
                <li className="mono" style={{ fontSize: 11 }}>14:22 · Received from form</li>
                <li className="mono" style={{ fontSize: 11 }}>14:23 · Catastro matched</li>
                <li className="mono" style={{ fontSize: 11 }}>14:24 · Auto-valuation ready</li>
              </ul>
            </div>
          </div>
          <div>
            <div className="eyebrow">{t("adm_card_auto")}</div>
            <div style={{ marginTop: 14, padding: 20, background: "var(--ivory)", borderLeft: "2px solid var(--gold)" }}>
              <div style={{ fontSize: 13, color: "var(--ink-60)" }}>Market: <b style={{ color: "var(--ink)" }}>305 000 €</b></div>
              <div style={{ fontSize: 13, marginTop: 4 }}>Target: <b style={{ color: "var(--gold-deep)" }}>325 000 – 340 000 €</b></div>
            </div>
            <div style={{ marginTop: 24 }}>
              <div className="label">{t("adm_card_adjust")}</div>
              <div style={{ display: "flex", gap: 10, marginTop: 8 }}>
                <input className="input" defaultValue="325000" />
                <input className="input" defaultValue="340000" />
              </div>
            </div>
            <div style={{ marginTop: 20 }}>
              <div className="label">{t("adm_card_notes")}</div>
              <textarea className="input" rows={3} style={{ marginTop: 6, minHeight: 90, resize: "vertical" }} />
            </div>
            <div style={{ marginTop: 24, display: "grid", gap: 10 }}>
              <button className="btn btn-gold">{t("adm_card_send")}</button>
              <button className="btn btn-ghost">{t("adm_card_assign")}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function AdminClients() {
  return (
    <div className="container rise">
      <div className="eyebrow">02</div>
      <h1 style={{ marginTop: 12, fontSize: 44 }}>Клиенты</h1>
      <div style={{ marginTop: 32, background: "var(--paper)", border: "1px solid var(--ink-10)" }}>
        {[
          { n: "María Fernández", p: "+34 612 345 678", e: "maria@mail.es", l: "ES", v: 3, d: "12 Apr 2026" },
          { n: "Ivan Petrov", p: "+34 698 221 044", e: "i.petrov@mail.ru", l: "RU", v: 2, d: "14 Apr 2026" },
          { n: "Hans Müller", p: "+49 170 444 888", e: "h.muller@mail.de", l: "EN", v: 1, d: "18 Apr 2026" },
          { n: "Laura Giménez", p: "+34 600 147 852", e: "l.gimenez@mail.es", l: "ES", v: 1, d: "22 Apr 2026" },
        ].map((r, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 80px 120px 120px", padding: "18px 24px", borderBottom: "1px solid var(--ink-10)", fontSize: 13, alignItems: "center" }}>
            <div style={{ fontFamily: "var(--serif)", fontSize: 16 }}>{r.n}</div>
            <div className="mono" style={{ fontSize: 12 }}>{r.p}</div>
            <div style={{ color: "var(--ink-60)" }}>{r.e}</div>
            <div className="mono" style={{ color: "var(--gold-deep)" }}>{r.l}</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 20 }}>{r.v}</div>
            <div style={{ color: "var(--ink-60)" }}>{r.d}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AdminProperties() {
  const items = [
    { a: "Calle Serrano 42, Madrid", p: "325–340k €", s: "3 valuations", ph: PHOTOS.apt1 },
    { a: "Paseo de Gracia 89, Barcelona", p: "830–880k €", s: "1 valuation", ph: PHOTOS.apt2 },
    { a: "Av. del Puerto 118, Valencia", p: "224–234k €", s: "1 valuation", ph: PHOTOS.apt3 },
    { a: "Calle Velázquez 80, Madrid", p: "280–295k €", s: "2 valuations", ph: PHOTOS.apt4 },
    { a: "Calle Mayor 7, Alicante", p: "165–178k €", s: "1 valuation", ph: PHOTOS.apt5 },
    { a: "Calle Goya 104, Madrid", p: "305–320k €", s: "2 valuations", ph: PHOTOS.apt6 },
  ];
  return (
    <div className="container rise">
      <div className="eyebrow">03</div>
      <h1 style={{ marginTop: 12, fontSize: 44 }}>Объекты</h1>
      <div className="stagger" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20, marginTop: 32 }}>
        {items.map((o, i) => (
          <div key={i} className="card card-hover" style={{ padding: 0, overflow: "hidden" }}>
            <div className="photo photo-hover" style={{ aspectRatio: "4/3" }}>
              <img src={o.ph} alt="" loading="lazy" />
            </div>
            <div style={{ padding: 24 }}>
              <div style={{ fontFamily: "var(--serif)", fontSize: 18 }}>{o.a}</div>
              <div className="mono" style={{ color: "var(--gold-deep)", marginTop: 8 }}>{o.p}</div>
              <div style={{ fontSize: 12, color: "var(--ink-60)", marginTop: 4 }}>{o.s}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AdminAnalytics() {
  const { t } = useI18n();
  const steps = [
    { l: t("adm_kpi_visitors"), v: 3842 },
    { l: t("adm_kpi_leads"),    v: 1654 },
    { l: t("adm_kpi_reports"),  v: 1421 },
    { l: t("adm_kpi_visits"),   v: 388 },
    { l: t("adm_kpi_excl"),     v: 142 },
  ];
  const max = steps[0].v;

  return (
    <div className="container rise">
      <div className="eyebrow">04</div>
      <h1 style={{ marginTop: 12, fontSize: 44 }}>Аналитика</h1>

      <div className="stagger" style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 16, marginTop: 40 }}>
        {steps.map((k, i) => {
          const v = useCountUp(k.v, 1600 + i * 200);
          return (
            <div key={i} className="card" style={{ borderTop: "2px solid var(--gold)" }}>
              <div className="eyebrow">{k.l}</div>
              <div className="num-lg" style={{ marginTop: 8 }}>{v}</div>
              {i > 0 && (
                <div className="mono" style={{ color: "var(--gold-deep)", marginTop: 6 }}>
                  {Math.round(k.v / steps[i - 1].v * 100)}% {t("adm_conv")}
                </div>
              )}
            </div>
          );
        })}
      </div>

      <div className="card" style={{ marginTop: 32, padding: 40 }}>
        <div className="eyebrow">{t("adm_funnel")}</div>
        <div style={{ display: "grid", gap: 14, marginTop: 24 }}>
          {steps.map((k, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "160px 1fr 80px", gap: 16, alignItems: "center" }}>
              <div style={{ fontSize: 13, color: "var(--ink-60)" }}>{k.l}</div>
              <div style={{ height: 26, background: "var(--ivory)", position: "relative" }}>
                <div style={{
                  height: "100%", width: `${(k.v / max) * 100}%`,
                  background: "linear-gradient(90deg, var(--gold-deep), var(--gold))",
                  transition: "width 1.4s var(--ease)",
                }} />
              </div>
              <div className="mono" style={{ color: "var(--gold-deep)", textAlign: "right" }}>{fmt(k.v)}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function AdminUsers() {
  return (
    <div className="container rise">
      <div className="eyebrow">05</div>
      <h1 style={{ marginTop: 12, fontSize: 44 }}>Пользователи</h1>
      <div style={{ marginTop: 32, background: "var(--paper)", border: "1px solid var(--ink-10)" }}>
        {[
          { n: "Carlos Tenorio", e: "c.tenorio@kn-elite.es", r: "Administrator", a: "Now" },
          { n: "Laura Ramos", e: "l.ramos@kn-elite.es", r: "Manager", a: "2h ago" },
          { n: "Adrián Vidal", e: "a.vidal@kn-elite.es", r: "Manager", a: "1d ago" },
          { n: "Nicolás K.", e: "owner@kn-elite.es", r: "Observer", a: "3d ago" },
        ].map((u, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "1.4fr 1.6fr 1fr 1fr", padding: "18px 24px", borderBottom: "1px solid var(--ink-10)", fontSize: 13, alignItems: "center" }}>
            <div style={{ fontFamily: "var(--serif)", fontSize: 16 }}>{u.n}</div>
            <div style={{ color: "var(--ink-60)" }}>{u.e}</div>
            <div><span className="chip chip-gold" style={{ fontSize: 10 }}>{u.r}</span></div>
            <div className="mono" style={{ color: "var(--ink-60)" }}>{u.a}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { AdminShell, AdminRequests, AdminRequestModal, AdminClients, AdminProperties, AdminAnalytics, AdminUsers });
