// Main app: routing, sidebar, theme, language, persistence wiring.

const { useReducer, useEffect: useEf, useState: useSt } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showTagline": true,
  "compactSidebar": false
}/*EDITMODE-END*/;

function TeamCountControl({ state, dispatch }) {
  const [draft, setDraft] = useSt(String(state.teams.length));
  useEf(() => { setDraft(String(state.teams.length)); }, [state.teams.length]);

  function commit(nRaw) {
    const v = Math.max(0, Math.min(200, parseInt(nRaw, 10) || 0));
    if (v === state.teams.length) { setDraft(String(state.teams.length)); return; }
    if (v > state.teams.length) {
      for (let i = state.teams.length; i < v; i++) dispatch({ type: "ADD_TEAM" });
    } else {
      const diff = state.teams.length - v;
      if (!confirm("¿Quitar " + diff + " equipo" + (diff === 1 ? "" : "s") + "?")) {
        setDraft(String(state.teams.length));
        return;
      }
      for (let i = state.teams.length; i > v; i--) {
        dispatch({ type: "DELETE_TEAM", id: state.teams[i - 1].id });
      }
    }
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <label style={{
        fontSize: 11, textTransform: "uppercase", letterSpacing: ".12em",
        color: "var(--muted)", fontWeight: 600,
      }}>
        Cantidad de equipos
      </label>
      <div className="row gap-8 center">
        <button
          className="btn btn-icon"
          onClick={() => commit(state.teams.length - 1)}
          disabled={state.teams.length === 0}
        >−</button>
        <input
          className="input mono"
          type="number"
          min="0" max="200"
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onBlur={() => commit(draft)}
          onKeyDown={(e) => {
            if (e.key === "Enter") { commit(draft); e.target.blur(); }
            if (e.key === "Escape") { setDraft(String(state.teams.length)); e.target.blur(); }
          }}
          style={{
            flex: 1, textAlign: "center",
            fontFamily: "var(--display)", fontSize: 22, padding: "6px 10px",
          }}
        />
        <button
          className="btn btn-icon"
          onClick={() => commit(state.teams.length + 1)}
        >+</button>
      </div>
      <div className="muted" style={{ fontSize: 10 }}>
        Escribe un número y presiona Enter, o usa los botones.
      </div>
    </div>
  );
}

function App() {
  const [state, dispatch] = useReducer(window.tournamentReducer, null, window.loadTournamentState);
  const [route, setRoute] = useSt(() => location.hash.slice(1) || "dashboard");

  // Auto-save on every change
  const [lastSavedAt, setLastSavedAt] = useSt(state.lastSavedAt);
  useEf(() => {
    window.saveTournamentState(state);
    setLastSavedAt(Date.now());
  }, [state]);

  // Hash routing
  useEf(() => {
    const onHash = () => setRoute(location.hash.slice(1) || "dashboard");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Apply theme
  useEf(() => {
    document.documentElement.setAttribute("data-theme", state.meta.theme || "dark");
  }, [state.meta.theme]);

  const lang = state.meta.lang || "es";
  const t = (key) => (window.I18N[lang] && window.I18N[lang][key]) || key;
  const setLang = (l) => dispatch({ type: "SET_META", patch: { lang: l } });
  const setTheme = (th) => dispatch({ type: "SET_META", patch: { theme: th } });

  function goto(r) {
    location.hash = r;
    setRoute(r);
  }

  // Tweaks
  const [tweaks, setTweaks] = useSt(TWEAK_DEFAULTS);
  function setTweak(k, v) {
    const patch = typeof k === "object" ? k : { [k]: v };
    setTweaks((t) => ({ ...t, ...patch }));
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: patch }, "*");
  }

  const NAV = [
    { section: "section_tournament", items: [
      { id: "dashboard", icon: "🏠", label: "nav_dashboard" },
      { id: "teams", icon: "👥", label: "nav_teams" },
      { id: "draw", icon: "🎰", label: "nav_draw" },
    ]},
    { section: "section_play", items: [
      { id: "calendar", icon: "📅", label: "nav_calendar" },
      { id: "standings", icon: "🏆", label: "nav_standings" },
      { id: "bracket", icon: "🌳", label: "nav_bracket" },
      { id: "live", icon: "🔴", label: "nav_live" },
      { id: "stats", icon: "📊", label: "nav_stats" },
    ]},
    { section: "section_data", items: [
      { id: "settings", icon: "⚙", label: "nav_settings" },
    ]},
  ];

  let view;
  switch (route) {
    case "teams": view = <TeamsView state={state} dispatch={dispatch} t={t} />; break;
    case "draw": view = <Tombola state={state} dispatch={dispatch} t={t} />; break;
    case "calendar": view = <CalendarView state={state} dispatch={dispatch} t={t} />; break;
    case "standings": view = <StandingsView state={state} t={t} />; break;
    case "bracket": view = <BracketView state={state} dispatch={dispatch} t={t} />; break;
    case "stats": view = <StatsView state={state} dispatch={dispatch} t={t} />; break;
    case "live": view = <LiveView state={state} dispatch={dispatch} t={t} />; break;
    case "settings": view = <SettingsView state={state} dispatch={dispatch} t={t} lang={lang} setLang={setLang} theme={state.meta.theme} setTheme={setTheme} />; break;
    default: view = <Dashboard state={state} t={t} goto={goto} />;
  }

  return (
    <div className="app">
      <aside className="sidebar">
        <div className="brand">
          <div className="brand-mark">
            <svg viewBox="0 0 44 52" xmlns="http://www.w3.org/2000/svg">
              <defs>
                {/* Gold metallic frame */}
                <linearGradient id="goldMetal" x1="0" y1="0" x2="0.65" y2="1">
                  <stop offset="0%"   stopColor="#FFF8C0"/>
                  <stop offset="18%"  stopColor="#F5C842"/>
                  <stop offset="48%"  stopColor="#B8760E"/>
                  <stop offset="72%"  stopColor="#E8A830"/>
                  <stop offset="100%" stopColor="#FFE580"/>
                </linearGradient>
                {/* Deep navy body */}
                <linearGradient id="navyBody" x1="0.15" y1="0" x2="0.88" y2="1">
                  <stop offset="0%"   stopColor="#1E3070"/>
                  <stop offset="40%"  stopColor="#0D1845"/>
                  <stop offset="100%" stopColor="#050A20"/>
                </linearGradient>
                {/* 3-D dome radial highlight */}
                <radialGradient id="dome3d" cx="30%" cy="16%" r="58%">
                  <stop offset="0%"   stopColor="rgba(255,255,255,0.22)"/>
                  <stop offset="55%"  stopColor="rgba(255,255,255,0.05)"/>
                  <stop offset="100%" stopColor="rgba(0,0,0,0.10)"/>
                </radialGradient>
                {/* Edge inner glow (blue) */}
                <radialGradient id="edgeGlow" cx="50%" cy="50%" r="50%">
                  <stop offset="60%"  stopColor="rgba(76,127,255,0)"/>
                  <stop offset="100%" stopColor="rgba(76,127,255,0.18)"/>
                </radialGradient>
                {/* Gold star fill */}
                <linearGradient id="starFill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%"   stopColor="#FFF6B0"/>
                  <stop offset="100%" stopColor="#D98A10"/>
                </linearGradient>
                {/* Building fill white-to-bluewhite */}
                <linearGradient id="crownFill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%"   stopColor="rgba(220,235,255,1)"/>
                  <stop offset="100%" stopColor="rgba(140,170,240,0.85)"/>
                </linearGradient>
                {/* Bottom vignette */}
                <linearGradient id="vignette" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%"   stopColor="rgba(0,0,0,0)"/>
                  <stop offset="100%" stopColor="rgba(0,0,0,0.30)"/>
                </linearGradient>
                {/* Night sky */}
                <linearGradient id="skyGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%"   stopColor="#04040C"/>
                  <stop offset="50%"  stopColor="#0B1232"/>
                  <stop offset="100%" stopColor="#14204A"/>
                </linearGradient>
                {/* Hill fill */}
                <linearGradient id="hillGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%"   stopColor="#1C3A22"/>
                  <stop offset="100%" stopColor="#0D1E12"/>
                </linearGradient>
                {/* Clip to inner shield body */}
                <clipPath id="shieldClip">
                  <path d="M22 3.8 L41 11 L41 31 Q41 47.5 22 50.5 Q3 47.5 3 31 L3 11 Z"/>
                </clipPath>
              </defs>

              {/* ── Layer 1: far drop shadow ── */}
              <path d="M22 1 L43 9 L43 31 Q43 49 22 52 Q1 49 1 31 L1 9 Z"
                fill="#000510" opacity="0.45" transform="translate(3,4)"/>
              {/* ── Layer 2: near shadow ── */}
              <path d="M22 1 L43 9 L43 31 Q43 49 22 52 Q1 49 1 31 L1 9 Z"
                fill="#000A1E" opacity="0.35" transform="translate(1.2,2)"/>

              {/* ── Layer 3: gold outer frame ── */}
              <path d="M22 0.5 L43.5 8.5 L43.5 31.5 Q43.5 49.5 22 52.5 Q0.5 49.5 0.5 31.5 L0.5 8.5 Z"
                fill="url(#goldMetal)"/>

              {/* ── Layer 4: dark navy body ── */}
              <path d="M22 3.8 L41 11 L41 31 Q41 47.5 22 50.5 Q3 47.5 3 31 L3 11 Z"
                fill="url(#navyBody)"/>

              {/* ── Layer 5: 3D dome highlight ── */}
              <path d="M22 3.8 L41 11 L41 31 Q41 47.5 22 50.5 Q3 47.5 3 31 L3 11 Z"
                fill="url(#dome3d)"/>

              {/* ── Layer 6: edge blue inner glow ── */}
              <path d="M22 3.8 L41 11 L41 31 Q41 47.5 22 50.5 Q3 47.5 3 31 L3 11 Z"
                fill="url(#edgeGlow)"/>

              {/* ── Layer 7: bottom vignette ── */}
              <path d="M22 3.8 L41 11 L41 31 Q41 47.5 22 50.5 Q3 47.5 3 31 L3 11 Z"
                fill="url(#vignette)"/>

              {/* ── Illustrated night scene (clipped) ── */}
              <g clipPath="url(#shieldClip)">
                {/* Sky */}
                <rect x="3" y="3.8" width="38" height="47" fill="url(#skyGrad)"/>

                {/* Moon halo + crescent */}
                <circle cx="33" cy="10" r="5" fill="rgba(245,220,80,0.10)"/>
                <circle cx="33" cy="10" r="3.2" fill="#F5E86A"/>
                <circle cx="35"  cy="9"  r="2.8" fill="#060812"/>

                {/* Stars scattered in sky */}
                <circle cx="8"  cy="7"   r="0.65" fill="white" opacity="0.90"/>
                <circle cx="14" cy="5.5" r="0.50" fill="white" opacity="0.82"/>
                <circle cx="19" cy="9"   r="0.42" fill="white" opacity="0.75"/>
                <circle cx="25" cy="6.5" r="0.48" fill="white" opacity="0.85"/>
                <circle cx="10" cy="14"  r="0.36" fill="white" opacity="0.62"/>
                <circle cx="17" cy="16"  r="0.30" fill="white" opacity="0.55"/>
                <circle cx="28" cy="12"  r="0.34" fill="white" opacity="0.58"/>
                <circle cx="6"  cy="18"  r="0.28" fill="white" opacity="0.48"/>

                {/* Cerro / hill silhouette */}
                <path d="M3,50.5 L3,45 Q10,37 22,34 Q34,37 41,45 L41,50.5 Z"
                  fill="url(#hillGrad)"/>
                {/* Hill lighter crest edge */}
                <path d="M3,45 Q10,37 22,34 Q34,37 41,45"
                  fill="none" stroke="rgba(60,100,50,0.55)" strokeWidth="0.8"/>

                {/* ── Back row (small, dim) ── */}
                {/* Bk1: terracotta peaked */}
                <path d="M8,43 L8,37.5 L11.2,34 L14.4,37.5 L14.4,43 Z" fill="#7A2C10"/>
                {/* Bk2: gold-yellow peaked center (tallest back) */}
                <path d="M16,43 L16,33 L20.5,29 L25,33 L25,43 Z" fill="#8A6208"/>
                {/* Bk3: slate flat right */}
                <rect x="27" y="35.5" width="8" height="7.5" fill="#2C4258"/>
                <rect x="26.5" y="34.3" width="9" height="1.4" fill="#203040"/>
                {/* Bk4: tiny house far left */}
                <path d="M4.5,43 L4.5,38.5 L6.8,36.5 L9.1,38.5 L9.1,43 Z" fill="#5A2010"/>

                {/* Palm tree silhouette between back houses */}
                <rect x="25.5" y="37" width="0.9" height="6" fill="#1A1008"/>
                <path d="M26,37 Q22,34 20,31" fill="none" stroke="#1A3A10" strokeWidth="1.2" strokeLinecap="round"/>
                <path d="M26,37 Q28,33 32,32" fill="none" stroke="#1A3A10" strokeWidth="1.2" strokeLinecap="round"/>
                <path d="M26,37 Q25,32 24,29" fill="none" stroke="#1A3A10" strokeWidth="1.0" strokeLinecap="round"/>

                {/* ── Front row (bigger, brighter) ── */}
                {/* Fr1: peaked orange-red left */}
                <path d="M3,50.5 L3,43.5 L8.5,39.5 L14,43.5 L14,50.5 Z" fill="#B84A18"/>
                {/* Fr2: flat mustard-yellow center */}
                <rect x="15" y="39" width="10.5" height="11.5" fill="#C09015"/>
                <rect x="14.5" y="37.7" width="11.5" height="1.5" fill="#907010"/>
                {/* Fr2 water tank on roof */}
                <rect x="18" y="35.8" width="3" height="2" rx="0.6" fill="#707880"/>
                <rect x="19" y="34.5" width="1" height="1.4" fill="#505860"/>
                {/* Fr3: peaked crimson right */}
                <path d="M26.5,50.5 L26.5,43.5 L31,40 L35.5,43.5 L35.5,50.5 Z" fill="#A02E14"/>
                {/* Fr4: flat steel-blue far right */}
                <rect x="36.5" y="42.5" width="4.5" height="8" fill="#3A5870"/>
                <rect x="36" y="41.2" width="5.5" height="1.4" fill="#2A4055"/>

                {/* ── Windows (bright, pop against dark walls) ── */}
                {/* Bk1 */}
                <rect x="9.3"  y="38.5" width="1.8" height="2.2" rx="0.25" fill="#FFE050" opacity="0.88"/>
                <rect x="12"   y="38.5" width="1.8" height="2.2" rx="0.25" fill="#FFE050" opacity="0.68"/>
                {/* Bk2 */}
                <rect x="17.5" y="34.5" width="2"   height="2.5" rx="0.25" fill="#FFE050" opacity="0.88"/>
                <rect x="21"   y="34.5" width="2"   height="2.5" rx="0.25" fill="#FFE050" opacity="0.70"/>
                <rect x="17.5" y="38.5" width="2"   height="2.5" rx="0.25" fill="#FFE050" opacity="0.65"/>
                <rect x="21"   y="38.5" width="2"   height="2.5" rx="0.25" fill="#FFE050" opacity="0.50"/>
                {/* Bk3 */}
                <rect x="28.2" y="37"   width="1.8" height="2.2" rx="0.25" fill="#FFE050" opacity="0.80"/>
                <rect x="31"   y="37"   width="1.8" height="2.2" rx="0.25" fill="#FFE050" opacity="0.60"/>
                {/* Fr1 */}
                <rect x="5"    y="45"   width="2.3" height="2.8" rx="0.25" fill="#FFE050" opacity="0.95"/>
                <rect x="9.5"  y="45"   width="2.3" height="2.8" rx="0.25" fill="#FFE050" opacity="0.78"/>
                {/* Fr2 */}
                <rect x="16.2" y="41"   width="2.5" height="3"   rx="0.25" fill="#FFE050" opacity="0.95"/>
                <rect x="20.3" y="41"   width="2.5" height="3"   rx="0.25" fill="#FFE050" opacity="0.80"/>
                <rect x="16.2" y="45.5" width="2.5" height="3"   rx="0.25" fill="#FFE050" opacity="0.68"/>
                {/* Fr2 door */}
                <rect x="22.8" y="46.5" width="2.2" height="4"   rx="0.4"  fill="rgba(60,30,8,0.80)"/>
                {/* Fr3 */}
                <rect x="28"   y="45"   width="2.3" height="2.8" rx="0.25" fill="#FFE050" opacity="0.92"/>
                <rect x="31.8" y="45"   width="2.3" height="2.8" rx="0.25" fill="#FFE050" opacity="0.75"/>
                {/* Fr4 */}
                <rect x="37.5" y="44"   width="1.8" height="2.2" rx="0.25" fill="#FFE050" opacity="0.82"/>

                {/* Ambient glow from lit windows onto hill */}
                <ellipse cx="22" cy="44" rx="8" ry="2" fill="rgba(255,220,50,0.06)"/>
              </g>

              {/* ── Outer crisp gold rim ── */}
              <path d="M22 0.5 L43.5 8.5 L43.5 31.5 Q43.5 49.5 22 52.5 Q0.5 49.5 0.5 31.5 L0.5 8.5 Z"
                fill="none" stroke="rgba(255,240,140,0.35)" strokeWidth="0.6"/>
              {/* Inner body rim */}
              <path d="M22 3.8 L41 11 L41 31 Q41 47.5 22 50.5 Q3 47.5 3 31 L3 11 Z"
                fill="none" stroke="rgba(76,127,255,0.22)" strokeWidth="0.7"/>
            </svg>
          </div>
          <div className="brand-name">
            {t("appName")}
            {tweaks.showTagline && <small>{t("appTagline")}</small>}
          </div>
        </div>
        {NAV.map((sec) => (
          <React.Fragment key={sec.section}>
            <div className="nav-section">{t(sec.section)}</div>
            {sec.items.map((item) => (
              <button
                key={item.id}
                className={"nav-item " + (route === item.id ? "active" : "")}
                onClick={() => goto(item.id)}
              >
                <span className="icon" style={{ fontSize: 16, lineHeight: 1 }}>{item.icon}</span>
                <span>{t(item.label)}</span>
              </button>
            ))}
          </React.Fragment>
        ))}
        <div className="nav-spacer"></div>
        <div className="row gap-8" style={{ padding: "8px 6px" }}>
          <button
            className="btn btn-ghost"
            style={{ flex: 1, fontSize: 11, padding: "6px 8px" }}
            onClick={() => setLang(lang === "es" ? "en" : "es")}
            title="Idioma / Language"
          >
            🌐 {lang.toUpperCase()}
          </button>
          <button
            className="btn btn-ghost"
            style={{ flex: 1, fontSize: 11, padding: "6px 8px" }}
            onClick={() => setTheme(state.meta.theme === "dark" ? "light" : "dark")}
            title="Tema / Theme"
          >
            {state.meta.theme === "dark" ? "☀" : "🌙"} {state.meta.theme === "dark" ? "LIGHT" : "DARK"}
          </button>
        </div>
        <div className="nav-meta">
          <span className="muted">{t("last_saved")} </span>
          <span className="mono">{new Date(lastSavedAt).toLocaleTimeString().slice(0, 5)}</span>
        </div>
      </aside>
      <main className="main">{view}</main>

      {/* Tweaks panel */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="App">
          <TweakToggle label="Mostrar tagline" value={tweaks.showTagline}
            onChange={(v) => setTweak("showTagline", v)} />
          <TweakRadio
            label="Tema"
            value={state.meta.theme || "dark"}
            options={[{ label: "Dark", value: "dark" }, { label: "Light", value: "light" }]}
            onChange={(v) => setTheme(v)}
          />
          <TweakRadio
            label="Idioma"
            value={lang}
            options={[{ label: "ES", value: "es" }, { label: "EN", value: "en" }]}
            onChange={setLang}
          />
        </TweakSection>
        <TweakSection label="Equipos">
          <div className="row gap-8">
            <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => dispatch({ type: "ADD_TEAM" })}>
              + Equipo
            </button>
            <button className="btn" style={{ flex: 1 }} onClick={() => {
              if (state.teams.length === 0) return;
              if (confirm("¿Quitar el último equipo?")) {
                dispatch({ type: "DELETE_TEAM", id: state.teams[state.teams.length - 1].id });
              }
            }}>− Equipo</button>
          </div>
          <TeamCountControl state={state} dispatch={dispatch} />
        </TweakSection>
        <TweakSection label="Grupos">
          <div className="row gap-8">
            <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => dispatch({ type: "ADD_GROUP" })}>+ Grupo</button>
            <button className="btn" style={{ flex: 1 }} onClick={() => {
              const last = state.groups[state.groups.length - 1];
              if (!last) return;
              dispatch({ type: "REMOVE_GROUP", id: last.id });
            }}>− Grupo</button>
          </div>
        </TweakSection>
        <TweakSection label="Datos">
          <TweakButton label="Exportar JSON" onClick={() => {
            const data = JSON.stringify(state, null, 2);
            const blob = new Blob([data], { type: "application/json" });
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url; a.download = "torneo.json"; a.click();
            URL.revokeObjectURL(url);
          }} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
