// pages.jsx — Páginas para Verduras Frescas RD

// ───────────────────────────────────────────────────────────
// HOME
// ───────────────────────────────────────────────────────────
const HomePage = ({ navigate, onAdd, onOpenProduct, justAddedId, openCart, showImages, gridCols }) => {
  const featured = window.PRODUCTS.filter(p => ['thai-chili','mango','papaya','aguacate-caribe','berenjena-china','aji-largo','scotch-bonnet','pina-verde','menta','romero','limoncillo','albahaca'].includes(p.id));
  return (
    <>
      {/* HERO — split: text + circle image, mint pastel bg */}
      <section className="hero-cv">
        <div className="hero-cv-inner">
          <div className="hero-cv-copy">
            <h1 className="hero-cv-title">Casa Viva SRL</h1>
            <p className="hero-cv-lead">
              Traemos para ti las frutas y verduras locales más frescas, directo
              del campo para asegurar calidad y sabor en cada uno de tus platos.
            </p>
            <div className="hero-cv-cta">
              <button className="btn btn-primary" onClick={() => navigate('productos')}>
                Cotiza Ya
              </button>
            </div>
          </div>
          <div className="hero-cv-media">
            <Placeholder
              label="hero · tomates y lechuga frescos"
              tint={['oklch(72% 0.18 30)', 'oklch(48% 0.18 30)']}
            />
          </div>
        </div>
      </section>

      {/* NUEVAS CATEGORÍAS — 3 cards con foto, centrado */}
      <section className="section section-center">
        <div className="section-title">
          <h2 className="h-section">Nuevas Categorías</h2>
          <p className="section-sub">Descubre la mejor selección de productos locales cultivados con amor, directo a tu hogar.</p>
        </div>
        <div className="hero-cats">
          {window.HOME_CATS.map(c => (
            <button key={c.id} className="hero-cat" onClick={() => navigate('productos', { cat: c.id })}>
              <div className="hero-cat-media">
                <Placeholder label={`${c.label.toLowerCase()}.jpg`} tint={c.tint} />
              </div>
              <div className="hero-cat-body">
                <h4>{c.label}</h4>
                <p>{c.desc}</p>
              </div>
            </button>
          ))}
        </div>
      </section>

      {/* CATÁLOGO DE PRODUCTOS */}
      <section className="section section-center" style={{ paddingTop: 0 }}>
        <div className="section-title">
          <h2 className="h-section">Catálogo de productos</h2>
        </div>
        <div className="prod-grid" style={{ '--cols': gridCols }}>
          {featured.map(p => (
            <ProductCard
              key={p.id}
              p={p}
              onAdd={onAdd}
              onOpen={onOpenProduct}
              justAdded={justAddedId === p.id}
              showImages={showImages}
            />
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 48 }}>
          <button className="btn btn-secondary" onClick={() => navigate('productos')}>
            Ver catálogo completo
          </button>
        </div>
      </section>

      {/* RÁPIDO Y FÁCIL */}
      <section className="rf-section">
        <div className="section section-center">
          <div className="section-title">
            <h2 className="h-section">Rápido y Fácil</h2>
          </div>
          <div className="rf-grid">
            <div className="rf-card">
              <div className="rf-icon"><Icon name="phone" size={26} /></div>
              <div className="rf-num">+1 809 555 0123</div>
              <p>Llámanos ahora para realizar un pedido personalizado y con todos los detalles.</p>
            </div>
            <div className="rf-card">
              <div className="rf-icon"><Icon name="mail" size={24} /></div>
              <div className="rf-num">pedidos@casaviva.do</div>
              <p>Envíanos un mensaje para obtener la lista de productos y datos de entrega.</p>
            </div>
            <div className="rf-card">
              <div className="rf-icon"><Icon name="truck" size={26} /></div>
              <div className="rf-num">Entrega Rápida</div>
              <p>Nuestros productos se eligen diariamente para darte la mayor calidad.</p>
            </div>
          </div>
          <div className="rf-end">
            <a href="tel:+18095550123" className="btn btn-primary">Llama Ahora</a>
          </div>
        </div>
      </section>

      {/* BANDA AMARILLA con slogan */}
      <section className="slogan-band">
        <div className="slogan-band-inner">
          <h2 className="slogan-text">El camino más corto desde el huerto hasta tu mesa familiar.</h2>
        </div>
      </section>
    </>
  );
};

// ───────────────────────────────────────────────────────────
// PRODUCTOS
// ───────────────────────────────────────────────────────────
const ProductsPage = ({ filter, setFilter, search, setSearch, onAdd, onOpenProduct, justAddedId, gridCols, showImages }) => {
  const filtered = window.PRODUCTS.filter(p => {
    const matchCat = filter === 'todos' || p.cat === filter;
    const matchSearch = !search || p.name.toLowerCase().includes(search.toLowerCase()) || p.cat.includes(search.toLowerCase());
    return matchCat && matchSearch;
  });
  return (
    <section className="section">
      <div className="section-head" style={{ marginBottom: 28 }}>
        <div>
          <div className="eyebrow">Catálogo</div>
          <h1 className="h-section">Todos los <em style={{ color: 'var(--primary)' }}>productos</em></h1>
        </div>
        <p className="lead">
          Selecciona lo que necesitas y arma tu canasta. Te confirmamos
          disponibilidad y precio por WhatsApp o correo antes de despachar.
        </p>
      </div>

      <div className="filter-bar">
        <div className="search" style={{ background: 'var(--paper-2)' }}>
          <Icon name="search" size={16} />
          <input
            placeholder="Buscar tomate, piña, combo…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        {window.CATEGORIES.map(c => (
          <button
            key={c.id}
            className="chip"
            aria-pressed={filter === c.id}
            onClick={() => setFilter(c.id)}
          >{c.label}</button>
        ))}
        <span className="filter-result">{filtered.length} resultados</span>
      </div>

      {filtered.length === 0 ? (
        <div className="empty" style={{ padding: '80px 20px' }}>
          <div className="empty-ill">∅</div>
          <h4>No encontramos productos</h4>
          <p>Prueba con otra palabra o limpia los filtros.</p>
          <button className="btn btn-ghost" onClick={() => { setFilter('todos'); setSearch(''); }}>Limpiar filtros</button>
        </div>
      ) : (
        <div className="prod-grid" style={{ '--cols': gridCols }}>
          {filtered.map(p => (
            <ProductCard
              key={p.id}
              p={p}
              onAdd={onAdd}
              onOpen={onOpenProduct}
              justAdded={justAddedId === p.id}
              showImages={showImages}
            />
          ))}
        </div>
      )}
    </section>
  );
};

// ───────────────────────────────────────────────────────────
// PRODUCT DETAIL
// ───────────────────────────────────────────────────────────
const ProductDetailPage = ({ productId, onAdd, navigate, gridCols, showImages, justAddedId }) => {
  const p = window.PRODUCTS.find(x => x.id === productId);
  const [unit, setUnit] = useState(p?.unit || 'lb');
  const [qty, setQty] = useState(1);
  useEffect(() => { setUnit(p?.unit || 'lb'); setQty(1); }, [productId]);
  if (!p) return null;
  const related = window.PRODUCTS.filter(x => x.cat === p.cat && x.id !== p.id).slice(0, 4);
  return (
    <section className="section">
      <div style={{ marginBottom: 24, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-mute)', letterSpacing: '0.05em' }}>
        <a onClick={() => navigate('productos')} style={{ cursor: 'pointer', textDecoration: 'none', color: 'var(--ink-soft)' }}>← productos</a>
        <span style={{ margin: '0 8px' }}>/</span>
        <span>{p.cat}</span>
        <span style={{ margin: '0 8px' }}>/</span>
        <span style={{ color: 'var(--ink)' }}>{p.name}</span>
      </div>
      <div className="pdp">
        <div className="pdp-media">
          <Placeholder label={`${p.id}.jpg · foto principal`} tint={p.tint} photo={p.photo} />
        </div>
        <div className="pdp-info">
          <div className="eyebrow" style={{ marginBottom: 0 }}>{p.cat} · {p.origin}</div>
          <h1 className="h-display">{p.name}</h1>
          <p className="lead" style={{ fontSize: 17 }}>{p.desc}</p>
          <div className="pdp-divider">
            <div className="pdp-row"><span className="k">Origen</span><span className="v">{p.origin}, RD</span></div>
            <div className="pdp-row"><span className="k">Disponibilidad</span><span className="v">En stock · cosecha del día</span></div>
            <div className="pdp-row"><span className="k">Empaque</span><span className="v">Saco reutilizable</span></div>
            <div className="pdp-row"><span className="k">Entrega</span><span className="v">24h (RD)</span></div>
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Unidad</div>
            <div className="unit-select">
              {p.units.map(u => (
                <button key={u} aria-pressed={unit === u} onClick={() => setUnit(u)}>{u}</button>
              ))}
            </div>
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Cantidad</div>
            <div className="qty" style={{ width: 'fit-content' }}>
              <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
              <span style={{ minWidth: 40, fontSize: 15 }}>{qty}</span>
              <button onClick={() => setQty(qty + 1)}>+</button>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
            <button
              className="btn btn-primary"
              onClick={() => onAdd(p, qty, unit)}
              style={{ flex: 1 }}
            >
              {justAddedId === p.id ? '✓ Agregado al carrito' : 'Agregar al carrito'}
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, opacity: 0.7 }}>
                {qty} {unit}
              </span>
            </button>
          </div>
        </div>
      </div>

      {related.length > 0 && (
        <div style={{ marginTop: 80 }}>
          <div className="section-head">
            <div>
              <div className="eyebrow">Acompáñalo con</div>
              <h2 className="h-section">Otros de la familia</h2>
            </div>
          </div>
          <div className="prod-grid" style={{ '--cols': Math.min(4, gridCols) }}>
            {related.map(r => (
              <ProductCard key={r.id} p={r} onAdd={onAdd} onOpen={(id) => navigate('detalle', { productId: id })} justAdded={justAddedId === r.id} showImages={showImages} />
            ))}
          </div>
        </div>
      )}
    </section>
  );
};

// ───────────────────────────────────────────────────────────
// CART PAGE (full page)
// ───────────────────────────────────────────────────────────
const CartPage = ({ cart, onInc, onDec, onRemove, total, navigate, contact, openEmailForm }) => {
  const [loading, setLoading] = useState(false);
  
  const sendWA = async () => {
    setLoading(true);
    try {
      const response = await api.quotationAPI.getQuotationMessage('Usuario');
      if (response.success) {
        window.open(response.whatsappLink, '_blank');
      }
    } catch (error) {
      alert('Error: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  if (cart.length === 0) {
    return (
      <section className="section">
        <div className="empty" style={{ padding: '120px 20px' }}>
          <div className="empty-ill">∅</div>
          <h4 style={{ fontSize: 40 }}>Tu carrito está vacío</h4>
          <p style={{ fontSize: 16, maxWidth: 400 }}>
            Aún no has agregado productos. Explora el catálogo y arma tu cotización en minutos.
          </p>
          <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
            <button className="btn btn-primary" onClick={() => navigate('productos')}>
              Ver productos <Icon name="arrow" size={16} />
            </button>
            <button className="btn btn-ghost" onClick={() => navigate('home')}>Volver al inicio</button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="section">
      <div className="section-head">
        <div>
          <div className="eyebrow">Tu cotización</div>
          <h1 className="h-section">Carrito de <em style={{ color: 'var(--primary)' }}>cotización</em></h1>
        </div>
        <p className="lead">
          Revisa cantidades y unidades. Al pedir cotización, te confirmamos
          disponibilidad y precio por WhatsApp o correo.
        </p>
      </div>

      <div className="cart-page">
        <div className="cart-list">
          {cart.map(it => (
            <CartItemRow key={it.id} item={it} onInc={onInc} onDec={onDec} onRemove={onRemove} />
          ))}
        </div>
        <div className="cart-side">
          <h3>Resumen</h3>
          <div className="summary">
            <div className="summary-row"><span>Productos ({cart.length})</span><span>{cart.reduce((s, i) => s + i.qty, 0)} unidades</span></div>
            <div className="summary-row"><span>Entrega</span><span>Por confirmar</span></div>
          </div>
          <div className="note">
            Te confirmaremos disponibilidad y precio por WhatsApp o correo en cuanto recibamos tu solicitud.
          </div>
          <button className="btn btn-wa btn-block" onClick={sendWA} disabled={loading}>
            <Icon name="wa" size={18} /> {loading ? 'Enviando...' : 'Cotizar por WhatsApp'}
          </button>
          <button className="btn btn-secondary btn-block" onClick={openEmailForm}>
            <Icon name="mail" size={16} /> Cotizar por correo
          </button>
          <button className="btn btn-ghost btn-block btn-sm" onClick={() => navigate('productos')}>
            Seguir comprando
          </button>
        </div>
      </div>
    </section>
  );
};

// ───────────────────────────────────────────────────────────
// CONTACTO
// ───────────────────────────────────────────────────────────
const ContactPage = ({ contact }) => {
  const [form, setForm] = useState({ name: '', email: '', subject: '', msg: '' });
  const [sent, setSent] = useState(false);
  const submit = (e) => { e.preventDefault(); setSent(true); };
  return (
    <section className="section">
      <div className="section-head" style={{ marginBottom: 48 }}>
        <div>
          <div className="eyebrow">Hablemos</div>
          <h1 className="h-section">Estamos a un <em style={{ color: 'var(--primary)' }}>WhatsApp</em> de distancia.</h1>
        </div>
        <p className="lead">
          Cotizaciones, dudas, pedidos especiales o sugerencias. Te respondemos
          rápido — somos un equipo pequeño y nos importa cada cliente.
        </p>
      </div>

      <div className="contact-grid">
        <div className="contact-info">
          <div className="info-card">
            <div className="info-icon"><Icon name="wa" size={20} /></div>
            <div>
              <h5>WhatsApp</h5>
              <p>Pedidos y cotizaciones en tiempo real.</p>
              <a href={`https://wa.me/${contact.waRaw}`} target="_blank">{contact.wa}</a>
            </div>
          </div>
          <div className="info-card">
            <div className="info-icon"><Icon name="mail" size={18} /></div>
            <div>
              <h5>Correo</h5>
              <p>Para empresas, restaurantes y pedidos grandes.</p>
              <a href={`mailto:${contact.email}`}>{contact.email}</a>
            </div>
          </div>
          <div className="info-card">
            <div className="info-icon"><Icon name="pin" size={18} /></div>
            <div>
              <h5>Ubicación</h5>
              <p>{contact.address}</p>
              <p style={{ fontSize: 13, color: 'var(--ink-mute)', marginTop: 4 }}>Solo bodega — atendemos pedidos a domicilio.</p>
            </div>
          </div>
          <div className="info-card">
            <div className="info-icon"><Icon name="clock" size={18} /></div>
            <div>
              <h5>Horario</h5>
              <p>{contact.hours}</p>
              <p style={{ fontSize: 13, color: 'var(--ink-mute)', marginTop: 4 }}>WhatsApp responde 7am–8pm todos los días.</p>
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
          <div className="map">
            <div className="map-grid" />
            <svg className="map-paths" viewBox="0 0 400 300" preserveAspectRatio="none">
              <path d="M 0 180 Q 100 160 200 175 T 400 165" stroke="oklch(70% 0.05 80)" strokeWidth="14" fill="none" strokeLinecap="round" opacity="0.4"/>
              <path d="M 80 0 Q 180 120 200 175 T 280 300" stroke="oklch(78% 0.04 80)" strokeWidth="8" fill="none" strokeLinecap="round" opacity="0.5"/>
              <path d="M 0 80 Q 120 100 230 60 T 400 90" stroke="oklch(82% 0.03 80)" strokeWidth="4" fill="none" strokeLinecap="round" opacity="0.5"/>
            </svg>
            <div className="map-pin">
              <div className="label">CASA VIVA · BODEGA NACO</div>
              <div className="dot" />
            </div>
          </div>

          {sent ? (
            <div style={{ background: 'var(--primary-100)', borderRadius: 'var(--r-lg)', padding: '32px 28px', textAlign: 'center' }}>
              <div className="eyebrow" style={{ color: 'var(--primary)' }}>Mensaje enviado</div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, margin: '8px 0 8px', fontWeight: 400 }}>¡Gracias, {form.name || 'amig@'}!</h3>
              <p style={{ color: 'var(--ink-soft)', margin: 0 }}>Te respondemos en menos de 24 horas.</p>
            </div>
          ) : (
            <form className="form" onSubmit={submit} style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 28 }}>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, margin: 0, fontWeight: 400 }}>Escríbenos</h3>
              <div className="field">
                <label>Nombre</label>
                <input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
              </div>
              <div className="field">
                <label>Correo</label>
                <input type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
              </div>
              <div className="field">
                <label>Asunto</label>
                <input value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })} />
              </div>
              <div className="field">
                <label>Mensaje</label>
                <textarea required value={form.msg} onChange={(e) => setForm({ ...form, msg: e.target.value })} />
              </div>
              <button type="submit" className="btn btn-primary btn-block">Enviar mensaje</button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
};

// ───────────────────────────────────────────────────────────
// LOGIN / SIGNUP
// ───────────────────────────────────────────────────────────
const LoginPage = ({ navigate, onLoggedIn }) => {
  const [mode, setMode] = useState('login'); // 'login' | 'signup'
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      let res;
      if (mode === 'login') {
        res = await window.authAPI.login(email, password);
      } else {
        res = await window.authAPI.signup(name, email, password, phone);
      }
      if (res && res.token) {
        window.CV_API.setAuthToken(res.token);
        onLoggedIn(res.user);
        navigate('home');
      } else {
        setError('Respuesta inesperada del servidor');
      }
    } catch (err) {
      setError(err.message || 'Error al iniciar sesión');
    } finally {
      setLoading(false);
    }
  };

  return (
    <section className="section section-center" style={{ paddingTop: 60, paddingBottom: 80 }}>
      <div style={{ maxWidth: 440, margin: '0 auto' }}>
        <h2 className="h-section" style={{ textAlign: 'center', marginBottom: 8 }}>
          {mode === 'login' ? 'Iniciar sesión' : 'Crear cuenta'}
        </h2>
        <p style={{ textAlign: 'center', color: 'var(--ink-soft, #666)', marginBottom: 28 }}>
          {mode === 'login'
            ? 'Accede a tu cuenta de Casa Viva SRL'
            : 'Regístrate para hacer pedidos más rápido'}
        </p>

        <form
          className="form"
          onSubmit={submit}
          style={{
            background: 'var(--paper)',
            border: '1px solid var(--line)',
            borderRadius: 'var(--r-lg)',
            padding: 28,
            display: 'flex',
            flexDirection: 'column',
            gap: 16,
          }}
        >
          {mode === 'signup' && (
            <>
              <div className="field">
                <label>Nombre completo</label>
                <input
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Tu nombre"
                />
              </div>
              <div className="field">
                <label>Teléfono (opcional)</label>
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="809-555-0123"
                />
              </div>
            </>
          )}

          <div className="field">
            <label>Correo</label>
            <input
              type="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="tu@correo.com"
            />
          </div>

          <div className="field">
            <label>Contraseña</label>
            <input
              type="password"
              required
              minLength={6}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Mínimo 6 caracteres"
            />
          </div>

          {error && (
            <div style={{
              padding: '10px 14px',
              background: 'rgba(220, 50, 50, 0.08)',
              color: '#b22',
              borderRadius: 8,
              fontSize: 14,
            }}>
              {error}
            </div>
          )}

          <button
            type="submit"
            className="btn btn-primary btn-block"
            disabled={loading}
          >
            {loading
              ? 'Procesando…'
              : mode === 'login' ? 'Iniciar sesión' : 'Crear cuenta'}
          </button>

          <div style={{ textAlign: 'center', fontSize: 14, marginTop: 4 }}>
            {mode === 'login' ? (
              <>
                ¿No tienes cuenta?{' '}
                <a
                  style={{ color: 'var(--primary)', cursor: 'pointer', textDecoration: 'underline' }}
                  onClick={() => { setMode('signup'); setError(''); }}
                >
                  Regístrate aquí
                </a>
              </>
            ) : (
              <>
                ¿Ya tienes cuenta?{' '}
                <a
                  style={{ color: 'var(--primary)', cursor: 'pointer', textDecoration: 'underline' }}
                  onClick={() => { setMode('login'); setError(''); }}
                >
                  Inicia sesión
                </a>
              </>
            )}
          </div>
        </form>
      </div>
    </section>
  );
};

Object.assign(window, {
  HomePage, ProductsPage, ProductDetailPage, CartPage, ContactPage, LoginPage,
});
