// app.jsx — orquestador principal con auth JWT + persistencia SQLite

// ── Temas (paletas boutique cálido + variantes) ────────────────
const THEMES = {
  arena: {
    bg: '#F6F1E8',
    card: '#FFFDF8',
    subtle: '#F0E8DA',
    input: '#FAF5EC',
    border: 'rgba(120, 90, 60, 0.14)',
    ink: '#3B2F22',
    muted: '#8A7A65',
    mutedSoft: '#B0A08A',
    accent: '#B08A5E',
    chipBg: 'rgba(255, 253, 248, 0.85)',
    chipFg: '#3B2F22',
    placeholderBg: '#EEE3D0',
    serif: '"Cormorant Garamond", "Playfair Display", Georgia, serif',
  },
  rosa: {
    bg: '#FAF2EC',
    card: '#FFFAF4',
    subtle: '#F2E3D9',
    input: '#FBF1E8',
    border: 'rgba(140, 80, 70, 0.14)',
    ink: '#3E2A24',
    muted: '#94736A',
    mutedSoft: '#BCA298',
    accent: '#B87766',
    chipBg: 'rgba(255, 250, 244, 0.85)',
    chipFg: '#3E2A24',
    placeholderBg: '#EFD9CD',
    serif: '"Cormorant Garamond", "Playfair Display", Georgia, serif',
  },
  salvia: {
    bg: '#F0EFE4',
    card: '#FBFAF2',
    subtle: '#E6E5D4',
    input: '#F5F4E9',
    border: 'rgba(80, 90, 60, 0.14)',
    ink: '#2E3424',
    muted: '#7C846E',
    mutedSoft: '#A8AD95',
    accent: '#8A9670',
    chipBg: 'rgba(251, 250, 242, 0.85)',
    chipFg: '#2E3424',
    placeholderBg: '#DCDCCA',
    serif: '"Cormorant Garamond", "Playfair Display", Georgia, serif',
  },
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "paleta": "arena",
  "densidad": "comoda",
  "vistaPorDefecto": "grid"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const theme = THEMES[t.paleta] || THEMES.arena;

  // ── Auth ─────────────────────────────────────────────────────
  const [token, setToken] = React.useState(() => localStorage.getItem('atelier_token'));
  const [currentUser, setCurrentUser] = React.useState(null);

  // ── Catálogo ─────────────────────────────────────────────────
  const [vestidos, setVestidos] = React.useState(null); // null = cargando
  const [loadError, setLoadError] = React.useState(null);
  const [screen, setScreen] = React.useState({ name: 'catalog' });
  const [view, setView] = React.useState(t.vistaPorDefecto);
  const [filters, setFilters] = React.useState({
    temporadas: [], tejidos: [], colores: [], q: '',
  });

  React.useEffect(() => {
    setView(t.vistaPorDefecto);
  }, [t.vistaPorDefecto]);

  // ── Helper fetch autenticado ──────────────────────────────────
  const apiFetch = React.useCallback((path, options = {}) => {
    return fetch(path, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        ...(options.headers || {}),
      },
    });
  }, [token]);

  // ── Cargar vestidos al autenticar ─────────────────────────────
  React.useEffect(() => {
    if (!token) { setVestidos(null); return; }
    setLoadError(null);
    apiFetch('/api/vestidos')
      .then(r => {
        if (r.status === 401) { logout(); return null; }
        return r.json();
      })
      .then(data => { if (data) setVestidos(data); })
      .catch(() => setLoadError('Error al cargar el catálogo'));
  }, [token]);

  // ── Acciones de autenticación ─────────────────────────────────
  const login = (newToken, user) => {
    localStorage.setItem('atelier_token', newToken);
    setToken(newToken);
    setCurrentUser(user);
  };

  const logout = () => {
    localStorage.removeItem('atelier_token');
    setToken(null);
    setCurrentUser(null);
    setVestidos(null);
    setScreen({ name: 'catalog' });
  };

  // ── Navegación ────────────────────────────────────────────────
  const openDetail  = (id) => setScreen({ name: 'detail', id });
  const openCatalog = () => setScreen({ name: 'catalog' });
  const openAdd     = () => setScreen({ name: 'form', mode: 'add' });
  const openEdit    = (id) => setScreen({ name: 'form', mode: 'edit', id });

  // ── CRUD (con persistencia en SQLite) ─────────────────────────
  const duplicar = async (id) => {
    const orig = vestidos.find(x => x.id === id);
    if (!orig) return;
    const copy = {
      ...JSON.parse(JSON.stringify(orig)),
      id: 'v-' + Math.random().toString(36).slice(2, 8),
      modelo: orig.modelo + ' (copia)',
    };
    try {
      await apiFetch('/api/vestidos', { method: 'POST', body: JSON.stringify(copy) });
      setVestidos([copy, ...vestidos]);
      setScreen({ name: 'detail', id: copy.id });
    } catch {
      alert('Error al duplicar el vestido');
    }
  };

  const eliminar = async (id) => {
    if (!confirm('¿Eliminar este vestido del catálogo?')) return;
    try {
      await apiFetch(`/api/vestidos/${id}`, { method: 'DELETE' });
      setVestidos(vestidos.filter(x => x.id !== id));
      openCatalog();
    } catch {
      alert('Error al eliminar el vestido');
    }
  };

  const saveVestido = async (v) => {
    try {
      if (screen.mode === 'edit' && screen.id) {
        await apiFetch(`/api/vestidos/${v.id}`, { method: 'PUT', body: JSON.stringify(v) });
        setVestidos(vestidos.map(x => x.id === v.id ? v : x));
        setScreen({ name: 'detail', id: v.id });
      } else {
        await apiFetch('/api/vestidos', { method: 'POST', body: JSON.stringify(v) });
        setVestidos([v, ...vestidos]);
        setScreen({ name: 'detail', id: v.id });
      }
    } catch {
      alert('Error al guardar el vestido');
    }
  };

  const resetCatalogo = async () => {
    if (!confirm('¿Restablecer catálogo a los vestidos de muestra?')) return;
    try {
      const res = await apiFetch('/api/vestidos/reset', { method: 'POST' });
      const data = await res.json();
      setVestidos(data);
      setScreen({ name: 'catalog' });
    } catch {
      alert('Error al restablecer el catálogo');
    }
  };

  // ── Pantalla de login ─────────────────────────────────────────
  if (!token) {
    return (
      <div style={{
        minHeight: '100vh', width: '100%',
        background: `linear-gradient(180deg, ${THEMES.arena.placeholderBg} 0%, ${THEMES.arena.bg} 100%)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24, boxSizing: 'border-box',
      }}>
        <style>{`
          body, html { margin: 0; padding: 0; background: ${THEMES.arena.bg}; }
          * { box-sizing: border-box; }
          input, button { font-family: inherit; }
        `}</style>
        <div style={{
          width: '100%', maxWidth: 480,
          background: THEMES.arena.bg,
          fontFamily: '"Inter", -apple-system, "SF Pro", system-ui, sans-serif',
          color: THEMES.arena.ink,
          borderRadius: 16,
          padding: 24,
        }}>
          <window.LoginView theme={THEMES.arena} onLogin={login} />
        </div>
      </div>
    );
  }

  // ── Pantalla de carga ─────────────────────────────────────────
  if (vestidos === null) {
    return (
      <div style={{
        minHeight: '100vh', width: '100%',
        background: `linear-gradient(180deg, ${theme.placeholderBg} 0%, ${theme.bg} 100%)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxSizing: 'border-box',
      }}>
        <style>{`body, html { margin: 0; padding: 0; } * { box-sizing: border-box; }`}</style>
        <div style={{
          display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center',
          gap: 16,
        }}>
          {loadError ? (
            <>
              <div style={{ fontFamily: theme.serif, fontSize: 18, color: theme.muted, textAlign: 'center', padding: '0 28px' }}>
                {loadError}
              </div>
              <button onClick={logout} style={{
                background: 'transparent', border: 0, color: theme.accent,
                fontSize: 14, cursor: 'pointer', textDecoration: 'underline',
              }}>Volver al inicio</button>
            </>
          ) : (
            <div style={{ fontFamily: theme.serif, fontSize: 20, color: theme.muted, letterSpacing: 0.3 }}>
              Cargando catálogo…
            </div>
          )}
        </div>
      </div>
    );
  }

  // ── Contenido principal ───────────────────────────────────────
  const currentVestido = screen.name === 'detail'
    ? vestidos.find(x => x.id === screen.id)
    : null;
  const initialForForm = screen.name === 'form' && screen.mode === 'edit'
    ? vestidos.find(x => x.id === screen.id)
    : null;

  let content;
  if (screen.name === 'catalog') {
    content = (
      <window.CatalogView
        vestidos={vestidos} theme={theme} density={t.densidad} view={view} setView={setView}
        filters={filters} setFilters={setFilters}
        onOpen={openDetail} onAdd={openAdd} />
    );
  } else if (screen.name === 'detail' && currentVestido) {
    content = (
      <window.DetailView vestido={currentVestido} theme={theme}
        onBack={openCatalog}
        onEdit={() => openEdit(currentVestido.id)}
        onDuplicate={() => duplicar(currentVestido.id)}
        onDelete={() => eliminar(currentVestido.id)} />
    );
  } else if (screen.name === 'form') {
    content = (
      <window.FormView theme={theme} initial={initialForForm}
        title={screen.mode === 'edit' ? 'Editar vestido' : 'Nuevo vestido'}
        onCancel={screen.mode === 'edit' ? () => setScreen({ name: 'detail', id: screen.id }) : openCatalog}
        onSave={saveVestido} />
    );
  } else {
    content = <div style={{ padding: 20, color: theme.muted }}>Vestido no encontrado.</div>;
  }

  return (
    <div style={{
      minHeight: '100vh', width: '100%',
      background: theme.bg,
      boxSizing: 'border-box',
    }}>
      <style>{`
        body, html { margin: 0; padding: 0; background: ${theme.bg}; }
        * { box-sizing: border-box; }
        .no-scrollbar::-webkit-scrollbar { display: none; }
        input, textarea, button { font-family: inherit; }
        input[type="search"]::-webkit-search-cancel-button { display: none; }
        button { -webkit-tap-highlight-color: transparent; }
      `}</style>

      <div style={{
        width: '100%',
        background: theme.bg,
        fontFamily: '"Inter", -apple-system, "SF Pro", system-ui, sans-serif',
        color: theme.ink,
      }}>
        {content}
      </div>

      <TweaksPanel>
        <TweakSection label="Paleta" />
        <TweakRadio label="Color" value={t.paleta}
                    options={[
                      { value: 'arena',  label: 'Arena' },
                      { value: 'rosa',   label: 'Rosa' },
                      { value: 'salvia', label: 'Salvia' },
                    ]}
                    onChange={(v) => setTweak('paleta', v)} />

        <TweakSection label="Catálogo" />
        <TweakRadio label="Vista por defecto" value={t.vistaPorDefecto}
                    options={[
                      { value: 'grid', label: 'Grid' },
                      { value: 'list', label: 'Lista' },
                    ]}
                    onChange={(v) => setTweak('vistaPorDefecto', v)} />
        <TweakRadio label="Densidad" value={t.densidad}
                    options={[
                      { value: 'compacta', label: 'Compacta' },
                      { value: 'comoda',   label: 'Cómoda' },
                    ]}
                    onChange={(v) => setTweak('densidad', v)} />

        <TweakSection label="Demo" />
        <TweakButton label="Reset catálogo" onClick={resetCatalogo} />

        <TweakSection label="Sesión" />
        <TweakButton
          label={`Cerrar sesión${currentUser ? ` (${currentUser.username})` : ''}`}
          onClick={logout} />
      </TweaksPanel>
    </div>
  );
}

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