/* Tienda online (public-facing) + Login screens */

const tecDigitsFromCode = (code) => {
  const m = String(code || '').match(/(\d{1,6})/);
  return typeof formatTecCodeDigitsInput === 'function'
    ? formatTecCodeDigitsInput(m ? m[1] : '')
    : String(m ? m[1] : '').replace(/\D/g, '').slice(0, 3);
};

const ProductImage = ({ product, theme, ratio = '1/1', label, accent }) => {
  if (product?.imageUrl) {
    return (
      <div style={{ position: 'relative', width: '100%', aspectRatio: ratio === 'auto' ? undefined : ratio, minHeight: ratio === 'auto' ? 280 : undefined, overflow: 'hidden', background: theme.bgInput }}>
        <img src={product.imageUrl} alt={product.name || ''} style={{
          width: '100%', height: '100%', objectFit: 'cover', display: 'block',
          objectPosition: `${product.coverFocusX ?? 50}% ${product.coverFocusY ?? 50}%`,
          minHeight: ratio === 'auto' ? 280 : undefined,
        }} />
      </div>
    );
  }
  return <PlaceholderImage icon={product?.icon || 'box'} label={label || product?.cat} theme={theme} ratio={ratio} accent={accent || theme.primary} />;
};

const ProductCardCompact = ({ p, theme, onOrder }) => (
  <Card theme={theme} hover style={{ padding: 0, overflow: 'hidden' }}>
    <div style={{ position: 'relative' }}>
      <ProductImage product={p} theme={theme} ratio="4/3" accent={theme.primary} />
      <Badge theme={theme} color={!p.inStock ? 'danger' : (p.stock < 10 ? 'warning' : 'success')} style={{ position: 'absolute', top: 8, right: 8 }}>
        {!p.inStock ? 'Agotado' : (p.stock < 10 ? `Quedan ${p.stock}` : 'En stock')}
      </Badge>
    </div>
    <div style={{ padding: '10px 12px 12px' }}>
      <div style={{ fontSize: 10, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>{p.cat}</div>
      <div style={{ fontWeight: 600, fontSize: 13, color: theme.text, fontFamily: 'Inter, sans-serif', marginTop: 2 }}>{p.name}</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}>
        <div style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 22, color: theme.primary, letterSpacing: 1 }}>${p.price}</div>
        <Btn theme={theme} size="sm" icon="cart" disabled={!p.inStock} onClick={() => onOrder(p)}>{p.inStock ? 'Ordenar' : 'Agotado'}</Btn>
      </div>
    </div>
  </Card>
);

const TiendaSection = ({ theme, onOrder, layout = 'grid', showStoreLink = false, compact = false, landingOnly = false }) => {
  const [cat, setCat] = React.useState('todos');
  const [products, setProducts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [loadError, setLoadError] = React.useState('');

  const loadProducts = React.useCallback(async () => {
    setLoading(true);
    setLoadError('');
    const { products: list, error } = await fetchProductsForTienda({ landingOnly });
    setProducts(list || []);
    if (error) setLoadError(error);
    setLoading(false);
  }, [landingOnly]);

  React.useEffect(() => {
    loadProducts();
    const onRefresh = () => { loadProducts(); };
    window.addEventListener('tecos:products-changed', onRefresh);
    return () => window.removeEventListener('tecos:products-changed', onRefresh);
  }, [loadProducts, landingOnly]);

  const cats = ['todos', ...Array.from(new Set(products.map(p => p.cat)))];
  const items = cat === 'todos' ? products : products.filter(p => p.cat === cat);

  const sectionPad = compact ? '80px 40px' : '100px 40px';

  const emptyBlock = (
    <section style={{ padding: sectionPad, background: theme.bg }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionTitle theme={theme} kicker="Tienda online" title="EQUÍPATE COMO PRO"
          sub="Productos del catálogo en Supabase (tabla products)." />
        {loading ? (
          <LoadingBlock theme={theme} label="Cargando productos…" />
        ) : loadError ? (
          <EmptyState theme={theme} title="No se pudo cargar la tienda" message={loadError} icon="warning" />
        ) : (
          <EmptyState theme={theme} title="Sin productos en tienda" message={landingOnly
            ? 'En Admin → Tienda online activa «Mostrar en landing» en tus productos del inventario.'
            : 'En Admin → Tienda online activa «Visible en tienda completa». Agrega productos en Inventario primero.'} icon="cart" />
        )}
      </div>
    </section>
  );

  if (loading || loadError || products.length === 0) return emptyBlock;

  if (compact) {
    return (
      <section style={{ padding: sectionPad, background: theme.bg }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <SectionTitle theme={theme} kicker="Tienda online"
            title="EQUÍPATE COMO PRO" sub="Productos oficiales Tecos Elite. Ordena con tu ID de alumno." />
          {showStoreLink && (
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8, marginTop: -16 }}>
              <a href="tienda.html" style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '9px 20px', borderRadius: 999,
                background: theme.primary, color: '#fff',
                fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 600,
                textDecoration: 'none',
              }}>Ver tienda completa →</a>
            </div>
          )}
          <CatFilter theme={theme} cats={cats} cat={cat} setCat={setCat} />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(168px, 1fr))', gap: 14 }}>
            {items.map(p => <ProductCardCompact key={p.id} p={p} theme={theme} onOrder={onOrder} />)}
          </div>
        </div>
      </section>
    );
  }

  if (layout === 'featured') {
    const featured = items[0];
    const rest = items.slice(1);
    return (
      <section style={{ padding: '100px 40px', background: theme.bg }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <SectionTitle theme={theme} kicker="Tienda online"
            title="EQUÍPATE COMO PRO" sub="Selecciona tu producto, levanta tu orden y confirma con transferencia." />
          {showStoreLink && (
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8, marginTop: -16 }}>
              <a href="tienda.html" style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '9px 20px', borderRadius: 999,
                background: theme.primary, color: '#fff',
                fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 600,
                textDecoration: 'none', letterSpacing: 0.3,
              }}>Ver tienda completa →</a>
            </div>
          )}
          <CatFilter theme={theme} cats={cats} cat={cat} setCat={setCat} />
          {featured && (
            <Card theme={theme} style={{ padding: 0, overflow: 'hidden', marginBottom: 18 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
                <div style={{ position: 'relative', minHeight: 340 }}>
                  <ProductImage product={featured} theme={theme} ratio="auto" accent={theme.primary} />
                  <Badge theme={theme} color="primary" soft={false} style={{ position: 'absolute', top: 16, left: 16 }}>Destacado</Badge>
                </div>
                <div style={{ padding: 36, display: 'grid', alignContent: 'center', gap: 14 }}>
                  <Badge theme={theme} color="textMute" style={{ alignSelf: 'flex-start' }}>{featured.cat}</Badge>
                  <h3 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 46, letterSpacing: 1, color: theme.text, margin: 0, fontWeight: 400 }}>{featured.name}</h3>
                  <p style={{ color: theme.textDim, fontFamily: 'Inter, sans-serif' }}>Producto oficial con logotipo bordado y tela de alta resistencia.</p>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <span style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 48, color: theme.primary, letterSpacing: 1 }}>${featured.price}</span>
                    <span style={{ color: theme.textMute, fontSize: 13, fontFamily: 'Inter, sans-serif' }}>MXN</span>
                  </div>
                  <div style={{ fontSize: 12, color: theme.textDim, fontFamily: 'Inter, sans-serif' }}>
                    {featured.inStock ? `${featured.stock} pieza(s) disponibles` : 'Agotado'}
                  </div>
                  <Btn theme={theme} icon="cart" size="lg" disabled={!featured.inStock} onClick={() => onOrder(featured)} style={{ alignSelf: 'flex-start' }}>Ordenar ahora</Btn>
                </div>
              </div>
            </Card>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
            {rest.map(p => <ProductCard key={p.id} p={p} theme={theme} onOrder={onOrder} />)}
          </div>
        </div>
      </section>
    );
  }

  if (layout === 'list') {
    return (
      <section style={{ padding: '100px 40px', background: theme.bg }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <SectionTitle theme={theme} kicker="Tienda online" title="EQUÍPATE COMO PRO"
            sub="Selecciona tu producto, levanta tu orden y confirma con transferencia." />
          {showStoreLink && (
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8, marginTop: -16 }}>
              <a href="tienda.html" style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '9px 20px', borderRadius: 999,
                background: theme.primary, color: '#fff',
                fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 600,
                textDecoration: 'none', letterSpacing: 0.3,
              }}>Ver tienda completa →</a>
            </div>
          )}
          <CatFilter theme={theme} cats={cats} cat={cat} setCat={setCat} />
          <Card theme={theme} style={{ padding: 0, overflow: 'hidden' }}>
            {items.map((p, i) => (
              <div key={p.id} style={{
                display: 'grid', gridTemplateColumns: '80px 1fr 1fr 100px 140px',
                gap: 16, padding: 14, alignItems: 'center',
                borderBottom: i < items.length - 1 ? `1px solid ${theme.border}` : 'none',
              }}>
                <div style={{ width: 70, height: 70 }}>
                  <ProductImage product={p} theme={theme} ratio="1/1" accent={theme.primary} />
                </div>
                <div>
                  <div style={{ fontWeight: 600, color: theme.text, fontFamily: 'Inter, sans-serif' }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: theme.textMute, fontFamily: 'Inter, sans-serif', marginTop: 4 }}>{p.cat}</div>
                </div>
                <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                  {p.tallas.map(t => (
                    <span key={t} style={{
                      padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700,
                      background: theme.bgInput, color: theme.textDim, border: `1px solid ${theme.border}`,
                      fontFamily: 'Inter, sans-serif',
                    }}>{t} ({getProductSizeStock(p, t)})</span>
                  ))}
                </div>
                <div style={{
                  fontFamily: 'Bebas Neue, sans-serif', fontSize: 28, color: theme.primary, letterSpacing: 1,
                }}>${p.price}</div>
                <Btn theme={theme} size="sm" icon="cart" disabled={!p.inStock} onClick={() => onOrder(p)}>{p.inStock ? 'Ordenar' : 'Agotado'}</Btn>
              </div>
            ))}
          </Card>
        </div>
      </section>
    );
  }

  // Default: grid
  return (
    <section style={{ padding: '100px 40px', background: theme.bg }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionTitle theme={theme} kicker="Tienda online"
          title="EQUÍPATE COMO PRO" sub="Selecciona tu producto, levanta tu orden y confirma con transferencia." />
        {showStoreLink && (
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8, marginTop: -16 }}>
            <a href="tienda.html" style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '9px 20px', borderRadius: 999,
              background: theme.primary, color: '#fff',
              fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 600,
              textDecoration: 'none', letterSpacing: 0.3,
            }}>Ver tienda completa →</a>
          </div>
        )}
        <CatFilter theme={theme} cats={cats} cat={cat} setCat={setCat} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16 }}>
          {items.map(p => <ProductCard key={p.id} p={p} theme={theme} onOrder={onOrder} />)}
        </div>
      </div>
    </section>
  );
};

const CatFilter = ({ theme, cats, cat, setCat }) => (
  <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
    {cats.map(t => (
      <button key={t} onClick={() => setCat(t)} style={{
        padding: '8px 16px', borderRadius: 999,
        background: cat === t ? theme.primary : theme.bgInput,
        color: cat === t ? '#fff' : theme.textDim,
        border: `1px solid ${cat === t ? theme.primary : theme.border}`,
        fontSize: 12, fontWeight: 600, letterSpacing: 0.5,
        textTransform: 'uppercase', cursor: 'pointer', fontFamily: 'Inter, sans-serif',
      }}>{t}</button>
    ))}
  </div>
);

const ProductCard = ({ p, theme, onOrder }) => (
  <Card theme={theme} hover style={{ padding: 0, overflow: 'hidden' }}>
    <div style={{ position: 'relative' }}>
      <ProductImage product={p} theme={theme} ratio="1/1" accent={theme.primary} />
      <Badge theme={theme} color={!p.inStock ? 'danger' : (p.stock < 10 ? 'warning' : 'success')} style={{ position: 'absolute', top: 10, right: 10 }}>
        {!p.inStock ? 'Agotado' : (p.stock < 10 ? `Quedan ${p.stock}` : 'En stock')}
      </Badge>
    </div>
    <div style={{ padding: 14 }}>
      <div style={{ fontSize: 10, color: theme.textMute, letterSpacing: 1, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>{p.cat}</div>
      <div style={{ fontWeight: 600, color: theme.text, marginTop: 4, fontFamily: 'Inter, sans-serif', fontSize: 14 }}>{p.name}</div>
      <div style={{ display: 'flex', gap: 4, marginTop: 8 }}>
        {p.tallas.slice(0, 4).map(t => (
          <span key={t} style={{
            padding: '2px 7px', borderRadius: 5, fontSize: 9, fontWeight: 700,
            background: theme.bgInput, color: theme.textDim, border: `1px solid ${theme.border}`,
            fontFamily: 'Inter, sans-serif',
          }}>{t}</span>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12 }}>
        <div style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 26, color: theme.primary, letterSpacing: 1 }}>${p.price}</div>
        <Btn theme={theme} size="sm" icon="cart" disabled={!p.inStock} onClick={() => onOrder(p)}>{p.inStock ? 'Ordenar' : 'Agotado'}</Btn>
      </div>
    </div>
  </Card>
);

/* ORDER FLOW (multi-step modal) */
const OrderFlow = ({ open, onClose, product, theme, onOrderPlaced }) => {
  const [step, setStep] = React.useState(1);
  const [size, setSize] = React.useState(product?.tallas[0] || '');
  const [qty, setQty] = React.useState(1);
  const [codeDigits, setCodeDigits] = React.useState('');
  const [form, setForm] = React.useState({
    studentName: '', tutorName: '', phone: '', email: '',
  });
  const [studentVerified, setStudentVerified] = React.useState(null);
  const [pendingStudent, setPendingStudent] = React.useState(null);
  const [lookupBusy, setLookupBusy] = React.useState(false);
  const [order, setOrder] = React.useState(null);
  const [receiptFile, setReceiptFile] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const fileRef = React.useRef(null);
  const lookupTimerRef = React.useRef(null);

  const sizeStock = (t) => getProductSizeStock(product, t);

  React.useEffect(() => {
    if (open) {
      setStep(1);
      setSize(product?.tallas[0] || '');
      setQty(1);
      setCodeDigits('');
      setForm({ studentName: '', tutorName: '', phone: '', email: '' });
      setStudentVerified(null);
      setPendingStudent(null);
      setLookupBusy(false);
      if (lookupTimerRef.current) clearTimeout(lookupTimerRef.current);
      setOrder(null);
      setReceiptFile(null);
      setError('');
    }
  }, [open, product]);

  React.useEffect(() => {
    if (!open || !product?.tallas?.length) return;
    const available = product.tallas.filter(t => sizeStock(t) > 0);
    const pick = available.includes(size) ? size : (available[0] || product.tallas[0]);
    setSize(pick);
    setQty(1);
  }, [open, product?.dbId]);

  if (!product) return null;
  const total = product.price * qty;
  const transferRef = order?.transfer_reference || order?.order_number || `ORD-${String(product.id).toUpperCase()}`;
  const displayOrderNum = order?.order_number || '#ORD-······';

  const setField = (key) => (e) => setForm(f => ({ ...f, [key]: e.target.value }));

  const fullStudentCode = typeof buildTecStudentCode === 'function'
    ? buildTecStudentCode(codeDigits)
    : (codeDigits ? `TEC${codeDigits.padStart(3, '0')}` : '');

  const applyStudentToForm = (found) => {
    if (!found) return;
    setStudentVerified(found);
    setPendingStudent(null);
    setCodeDigits(tecDigitsFromCode(found.code));
    setForm(f => ({
      ...f,
      studentName: found.full_name || '',
      tutorName: found.tutor_name || '',
      phone: found.tutor_phone || '',
      email: found.tutor_email || '',
    }));
  };

  const lookupStudentByCode = async (rawCode) => {
    const normalized = normalizeTecStudentCode(rawCode);
    if (!normalized) {
      setPendingStudent(null);
      return;
    }
    if (!isSupabaseReady()) return;
    setLookupBusy(true);
    setError('');
    try {
      const found = await lookupStudentCodePublic(rawCode);
      if (!found) {
        setPendingStudent(null);
        setStudentVerified(null);
        return;
      }
      if (found.status && found.status !== 'activo') {
        setPendingStudent(null);
        setStudentVerified(null);
        setError('Ese alumno no está activo. Contacta a la academia.');
        return;
      }
      setPendingStudent(found);
      setStudentVerified(null);
    } catch (e) {
      setPendingStudent(null);
      setError(e.message || 'No se pudo buscar el alumno.');
    }
    setLookupBusy(false);
  };

  const scheduleStudentLookup = (digits) => {
    if (lookupTimerRef.current) clearTimeout(lookupTimerRef.current);
    const code = typeof buildTecStudentCode === 'function' ? buildTecStudentCode(digits) : '';
    if (!code) {
      setPendingStudent(null);
      return;
    }
    lookupTimerRef.current = setTimeout(() => lookupStudentByCode(code), 450);
  };

  const onCodeDigitsChange = (d) => {
    setCodeDigits(d);
    setStudentVerified(null);
    setPendingStudent(null);
    setError('');
    scheduleStudentLookup(d);
  };

  const confirmStudentYes = () => applyStudentToForm(pendingStudent);

  const confirmStudentNo = () => {
    setPendingStudent(null);
    setStudentVerified(null);
  };

  const handleContinue = async () => {
    setError('');
    if (step === 1) {
      const avail = sizeStock(size);
      if (avail < qty) {
        setError(`Solo hay ${avail} pieza(s) en talla ${size}.`);
        return;
      }
      if (avail < 1) {
        setError('Esa talla no tiene stock. Elige otra.');
        return;
      }
    }
    if (step === 2) {
      const normalized = normalizeTecStudentCode(fullStudentCode);
      if (!normalized) {
        setError('Escribe el número de tu ID (ej. 001 o 067).');
        return;
      }
      if (pendingStudent && !studentVerified) {
        setError('Confirma con «Sí» o «No» si el ID te corresponde.');
        return;
      }
      if (!form.studentName.trim() || !form.tutorName.trim() || !form.phone.trim()) {
        setError('Completa nombre del alumno, tutor y teléfono.');
        return;
      }
      let verifiedStudent = studentVerified;
      if (isSupabaseReady() && !verifiedStudent) {
        setBusy(true);
        try {
          const found = await lookupStudentCodePublic(fullStudentCode);
          if (!found) {
            setError(`No existe un alumno activo con ID ${normalized}. Regístralo en Admin → Alumnos.`);
            setBusy(false);
            return;
          }
          if (found.status && found.status !== 'activo') {
            setError('Ese alumno no está activo. Contacta a la academia.');
            setBusy(false);
            return;
          }
          verifiedStudent = found;
          setStudentVerified(found);
        } catch (e) {
          setError(e.message || 'No se pudo validar el ID del alumno.');
          setBusy(false);
          return;
        }
        setBusy(false);
      }
      const finalCode = verifiedStudent?.code || normalized;
      const finalName = form.studentName.trim() || verifiedStudent?.full_name || '';
      const finalTutor = form.tutorName.trim() || verifiedStudent?.tutor_name || '';
      const finalPhone = form.phone.trim() || verifiedStudent?.tutor_phone || '';
      const finalEmail = form.email.trim() || verifiedStudent?.tutor_email || '';
      if (isSupabaseReady() && product.dbId) {
        setBusy(true);
        try {
          const created = await createGuestOrder({
            productId: product.dbId,
            size, qty,
            studentName: finalName,
            studentCode: finalCode,
            tutorName: finalTutor,
            phone: finalPhone,
            email: finalEmail,
          });
          setOrder(created);
          if (typeof notifyOrdersChanged === 'function') notifyOrdersChanged();
          window.dispatchNotificationsChanged?.();
        } catch (e) {
          setError(e.message || 'No se pudo crear la orden.');
          setBusy(false);
          return;
        }
        setBusy(false);
      } else if (isSupabaseReady() && !product.dbId) {
        setOrder({
          order_number: 'ORD-DEMO',
          transfer_reference: `ORD-${String(product.id).toUpperCase()}`,
          total,
        });
      } else {
        setOrder({
          order_number: 'ORD-DEMO',
          transfer_reference: `ORD-${String(product.id).toUpperCase()}`,
          total,
        });
      }
    }
    if (step === 4) {
      if (!receiptFile) {
        setError('Selecciona el comprobante de transferencia.');
        return;
      }
      if (isSupabaseReady() && order?.order_id) {
        setBusy(true);
        try {
          await uploadOrderReceipt({
            orderId: order.order_id,
            phone: form.phone,
            studentCode: studentVerified?.code || fullStudentCode,
            file: receiptFile,
          });
          if (typeof notifyComprobantesChanged === 'function') notifyComprobantesChanged();
          if (typeof notifyOrdersChanged === 'function') notifyOrdersChanged();
          window.dispatchNotificationsChanged?.();
        } catch (e) {
          setError(e.message || 'Error al subir el comprobante.');
          setBusy(false);
          return;
        }
        setBusy(false);
      } else {
        const mockOrder = {
          id: 'mock-ord-' + Date.now(),
          order_number: order?.order_number || displayOrderNum,
          total: order?.total ?? total,
          receipt_uploaded_at: new Date().toISOString(),
          transfer_reference: order?.transfer_reference || transferRef,
          guest_student_name: form.studentName,
          guest_student_code: studentVerified?.code || fullStudentCode,
          guest_tutor_name: form.tutorName,
          guest_phone: form.phone,
          order_items: [{ product_name: product.name, size, qty, unit_price: product.price }],
        };
        if (typeof window.pushMockOrdenTienda === 'function') window.pushMockOrdenTienda(mockOrder);
      }
      onOrderPlaced?.({
        orderId: order?.order_id,
        orderNumber: order?.order_number || displayOrderNum,
        total: order?.total ?? total,
        studentCode: studentVerified?.code || fullStudentCode,
        phone: form.phone,
        productName: product.name,
        icon: product.icon,
      });
    }
    setStep(s => s + 1);
  };

  const steps = ['Producto', 'Datos', 'Transferencia', 'Comprobante', 'Confirmación'];

  return (
    <Modal open={open} onClose={onClose} theme={theme} width={680}>
      {/* Header with steps */}
      <div style={{ padding: '20px 24px', borderBottom: `1px solid ${theme.border}` }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <h3 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 26, color: theme.text, letterSpacing: 1, margin: 0, fontWeight: 400 }}>NUEVA ORDEN</h3>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 8, background: theme.bgInput,
            border: `1px solid ${theme.border}`, color: theme.text, cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}><Icon name="x" size={16} /></button>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          {steps.map((s, i) => {
            const num = i + 1;
            const active = num === step, done = num < step;
            return (
              <React.Fragment key={s}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{
                    width: 26, height: 26, borderRadius: '50%',
                    background: done ? theme.success : active ? theme.primary : theme.bgInput,
                    color: done || active ? '#fff' : theme.textDim,
                    fontSize: 12, fontWeight: 700, display: 'grid', placeItems: 'center',
                    fontFamily: 'Inter, sans-serif',
                    boxShadow: active ? `0 0 0 4px ${theme.primary}33` : 'none',
                    transition: 'all .25s',
                  }}>{done ? <Icon name="check" size={14} /> : num}</div>
                  <span style={{
                    fontSize: 11, color: active ? theme.text : theme.textMute,
                    letterSpacing: 0.6, textTransform: 'uppercase', fontWeight: 600, fontFamily: 'Inter, sans-serif',
                  }}>{s}</span>
                </div>
                {i < steps.length - 1 && <div style={{ flex: 1, height: 1, background: done ? theme.success : theme.border }}></div>}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      <div style={{ padding: 24, minHeight: 360 }}>
        {step === 1 && (
          <div>
            <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 20, marginBottom: 20 }}>
              <ProductImage product={product} theme={theme} ratio="1/1" />
              <div>
                <Badge theme={theme} color="textMute">{product.cat}</Badge>
                <h4 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 26, color: theme.text, letterSpacing: 1, margin: '6px 0', fontWeight: 400 }}>{product.name}</h4>
                <div style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 36, color: theme.primary, letterSpacing: 1 }}>${product.price}</div>
              </div>
            </div>
            <div style={{ display: 'grid', gap: 16 }}>
              <div>
                <label style={{ fontSize: 11, fontWeight: 600, letterSpacing: 0.6, color: theme.textDim, textTransform: 'uppercase', marginBottom: 8, display: 'block' }}>Talla</label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {product.tallas.map(t => {
                    const st = sizeStock(t);
                    const disabled = st < 1;
                    return (
                      <button key={t} type="button" disabled={disabled} onClick={() => { setSize(t); setQty(1); setError(''); }} style={{
                        padding: '10px 14px', borderRadius: 8,
                        background: size === t ? theme.primary : theme.bgInput,
                        color: disabled ? theme.textMute : (size === t ? '#fff' : theme.text),
                        border: `1px solid ${size === t ? theme.primary : theme.border}`,
                        fontSize: 13, fontWeight: 700, cursor: disabled ? 'not-allowed' : 'pointer',
                        fontFamily: 'Inter, sans-serif', minWidth: 50, opacity: disabled ? 0.45 : 1,
                      }}>
                        {t}
                        <span style={{ display: 'block', fontSize: 9, fontWeight: 500, opacity: 0.85 }}>({st})</span>
                      </button>
                    );
                  })}
                </div>
              </div>
              <div>
                <label style={{ fontSize: 11, fontWeight: 600, letterSpacing: 0.6, color: theme.textDim, textTransform: 'uppercase', marginBottom: 8, display: 'block' }}>Cantidad</label>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <button onClick={() => setQty(Math.max(1, qty - 1))} style={navBtnQty(theme)}><Icon name="minus" size={14} /></button>
                  <div style={{
                    width: 60, height: 40, display: 'grid', placeItems: 'center',
                    background: theme.bgInput, border: `1px solid ${theme.border}`, borderRadius: 8,
                    fontSize: 16, fontWeight: 700, color: theme.text, fontFamily: 'Inter, sans-serif',
                  }}>{qty}</div>
                  <button onClick={() => setQty(Math.min(sizeStock(size), qty + 1))} style={navBtnQty(theme)}><Icon name="plus" size={14} /></button>
                </div>
              </div>
              <div style={{
                marginTop: 8, padding: 16, borderRadius: 10,
                background: theme.bgInput, border: `1px solid ${theme.border}`,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <span style={{ color: theme.textDim, fontFamily: 'Inter, sans-serif' }}>Total</span>
                  <span style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 32, color: theme.primary, letterSpacing: 1 }}>${total}</span>
                </div>
              </div>
            </div>
          </div>
        )}
        {error && (
          <div style={{ margin: '0 0 16px', padding: 12, borderRadius: 8, background: `${theme.danger}18`, color: theme.danger, fontSize: 13, fontFamily: 'Inter, sans-serif' }}>
            {error}
          </div>
        )}
        {step === 2 && (
          <div>
            <p style={{ margin: '0 0 14px', fontSize: 12, color: theme.textDim, fontFamily: 'Inter, sans-serif', lineHeight: 1.5 }}>
              El <strong style={{ color: theme.text }}>ID del alumno (TEC)</strong> es obligatorio. Escribe solo el número; el prefijo TEC ya está incluido (ej. 067 → TEC067).
            </p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div style={{ gridColumn: '1 / -1' }}>
                {typeof TecStudentIdField === 'function' ? (
                  <TecStudentIdField
                    theme={theme}
                    label="Número de ID *"
                    icon="medal"
                    digits={codeDigits}
                    onDigitsChange={onCodeDigitsChange}
                    onBlur={() => fullStudentCode && lookupStudentByCode(fullStudentCode)}
                  />
                ) : (
                  <Input theme={theme} label="ID del alumno *" placeholder="067" icon="medal" value={codeDigits}
                    onChange={(e) => onCodeDigitsChange(e.target.value.replace(/\D/g, '').slice(0, 3))}
                    onBlur={() => fullStudentCode && lookupStudentByCode(fullStudentCode)} />
                )}
              </div>
              <Input theme={theme} label="Nombre del alumno *" placeholder="Nombre completo" icon="user" value={form.studentName} onChange={setField('studentName')} />
              <Input theme={theme} label="Nombre del tutor *" placeholder="Padre / madre" icon="user" value={form.tutorName} onChange={setField('tutorName')} />
              <Input theme={theme} label="Teléfono *" placeholder="+52 ..." icon="wa" value={form.phone} onChange={setField('phone')} />
              <div style={{ gridColumn: '1 / -1' }}>
                <Input theme={theme} label="Correo electrónico" placeholder="correo@ejemplo.com" value={form.email} onChange={setField('email')} />
              </div>
            </div>
            {lookupBusy && (
              <p style={{ margin: '12px 0 0', fontSize: 12, color: theme.textDim, fontFamily: 'Inter, sans-serif' }}>Buscando alumno…</p>
            )}
            {pendingStudent && !studentVerified && (
              <StudentConfirmNeonBanner
                theme={theme}
                student={pendingStudent}
                glowColor={theme.primary}
                onYes={confirmStudentYes}
                onNo={confirmStudentNo}
                subtitle="Si eres esta persona, confirma y completamos tus datos automáticamente."
              />
            )}
            {studentVerified && (
              <div style={{
                marginTop: 14, padding: 12, borderRadius: 10,
                background: `${theme.success}18`, border: `1px solid ${theme.success}44`,
                fontSize: 12, fontFamily: 'Inter, sans-serif', color: theme.text,
              }}>
                Datos cargados: <strong>{studentVerified.code}</strong> — {studentVerified.full_name}
                {studentVerified.category ? ` · ${studentVerified.category}` : ''}
              </div>
            )}
          </div>
        )}
        {step === 3 && (
          <div>
            <TransferBankPanel theme={theme} purpose="tienda" reference={transferRef} amount={order?.total ?? total} />
            <p style={{ color: theme.textDim, fontSize: 13, fontFamily: 'Inter, sans-serif' }}>
              Después de realizar tu transferencia, en el siguiente paso podrás subir el comprobante.
            </p>
          </div>
        )}
        {step === 4 && (
          <div>
            <label style={{ fontSize: 11, fontWeight: 600, letterSpacing: 0.6, color: theme.textDim, textTransform: 'uppercase', marginBottom: 10, display: 'block' }}>Comprobante de transferencia</label>
            <input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp,application/pdf" style={{ display: 'none' }}
              onChange={e => { setReceiptFile(e.target.files?.[0] || null); setError(''); }} />
            <div onClick={() => fileRef.current?.click()} style={{
              border: `2px dashed ${theme.primary}55`, borderRadius: 12,
              padding: 40, textAlign: 'center', background: `${theme.primary}08`, cursor: 'pointer',
            }}>
              <div style={{ width: 60, height: 60, borderRadius: '50%', margin: '0 auto 12px', background: `${theme.primary}22`, color: theme.primary, display: 'grid', placeItems: 'center' }}>
                <Icon name="upload" size={28} />
              </div>
              <div style={{ color: theme.text, fontWeight: 600, fontFamily: 'Inter, sans-serif' }}>Arrastra tu comprobante aquí</div>
              <div style={{ color: theme.textDim, fontSize: 12, marginTop: 4, fontFamily: 'Inter, sans-serif' }}>o haz clic para seleccionar (PNG, JPG, PDF)</div>
            </div>
            {receiptFile && (
              <div style={{ marginTop: 16, padding: 12, borderRadius: 10, background: theme.bgInput, border: `1px solid ${theme.border}`, display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 42, height: 42, borderRadius: 8, background: theme.bgElev, display: 'grid', placeItems: 'center', color: theme.primary }}><Icon name="doc" size={20} /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ color: theme.text, fontSize: 13, fontWeight: 600, fontFamily: 'Inter, sans-serif' }}>{receiptFile.name}</div>
                  <div style={{ color: theme.textMute, fontSize: 11, fontFamily: 'Inter, sans-serif' }}>{Math.round(receiptFile.size / 1024)} KB · Listo para enviar</div>
                </div>
                <Icon name="check" size={18} style={{ color: theme.success }} />
              </div>
            )}
          </div>
        )}
        {step === 5 && (
          <div style={{ textAlign: 'center', padding: 30 }}>
            <div style={{
              width: 100, height: 100, borderRadius: '50%', margin: '0 auto 20px',
              background: `${theme.success}22`, color: theme.success,
              display: 'grid', placeItems: 'center',
              animation: 'pop .5s cubic-bezier(.2,.9,.3,1.4)',
              boxShadow: `0 0 0 8px ${theme.success}11`,
            }}><Icon name="check" size={50} /></div>
            <h3 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 40, color: theme.text, letterSpacing: 1, margin: 0, fontWeight: 400 }}>¡ORDEN RECIBIDA!</h3>
            <p style={{ color: theme.textDim, fontFamily: 'Inter, sans-serif', marginTop: 8 }}>
              Tu orden está en revisión. El administrador validará tu comprobante y el registro del alumno.
            </p>
            <div style={{
              marginTop: 20, padding: 16, borderRadius: 10, display: 'inline-flex', gap: 14, alignItems: 'center',
              background: theme.bgInput, border: `1px solid ${theme.border}`,
            }}>
              <div style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 24, color: theme.primary, letterSpacing: 1 }}>{displayOrderNum}</div>
              <StatusPill status="en_revision" theme={theme} />
            </div>
          </div>
        )}
      </div>

      <div style={{ padding: '16px 24px', borderTop: `1px solid ${theme.border}`, display: 'flex', justifyContent: 'space-between' }}>
        <Btn theme={theme} kind="ghost" onClick={() => step > 1 ? setStep(step - 1) : onClose()}>
          {step > 1 ? '← Atrás' : 'Cancelar'}
        </Btn>
        {step < 5 ? (
          <Btn theme={theme} icon="arrowRight" onClick={handleContinue} disabled={busy}>
            {busy ? 'Procesando…' : step === 4 ? 'Enviar orden' : 'Continuar'}
          </Btn>
        ) : (
          <Btn theme={theme} kind="success" icon="check" onClick={onClose}>Listo</Btn>
        )}
      </div>
    </Modal>
  );
};

const navBtnQty = (theme) => ({
  width: 40, height: 40, borderRadius: 8,
  background: theme.bgInput, border: `1px solid ${theme.border}`,
  color: theme.text, cursor: 'pointer',
  display: 'grid', placeItems: 'center',
});

function loginErrorMessage (err) {
  const msg = (err?.message || '').toLowerCase();
  if (msg.includes('invalid login') || msg.includes('invalid credentials')) {
    return 'Correo o contraseña incorrectos.';
  }
  if (msg.includes('email not confirmed')) {
    return 'Confirma tu correo (revisa tu bandeja) e intenta de nuevo.';
  }
  return err?.message || 'No se pudo iniciar sesión';
}

/* LOGIN SCREEN */
const LoginScreen = ({ theme, onLogin, onBack }) => {
  const [mode, setMode] = React.useState('alumno');
  const [infoModalOpen, setInfoModalOpen] = React.useState(false);
  const [studentDigits, setStudentDigits] = React.useState('');
  const [studentPassword, setStudentPassword] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [loginError, setLoginError] = React.useState('');
  const [loginBusy, setLoginBusy] = React.useState(false);

  const switchMode = (next) => {
    setMode(next);
    setLoginError('');
    setStudentDigits('');
    setStudentPassword('');
    setEmail('');
    setPassword('');
  };

  const handleSubmit = async () => {
    setLoginError('');

    if (mode === 'alumno') {
      const digits = String(studentDigits || '').replace(/\D/g, '').slice(0, 3);
      if (digits.length !== 3) {
        setLoginError('Escribe los 3 dígitos de tu ID de alumno (ej. 023, 100, 102).');
        return;
      }
      const code = `TEC${digits}`;
      if (!studentPassword.trim()) {
        setLoginError('Escribe tu contraseña.');
        return;
      }
      if (isSupabaseReady()) {
        setLoginBusy(true);
        try {
          const result = await verifyStudentPortalLogin(code, studentPassword);
          if (!result?.ok) {
            setLoginError(result?.error || 'No se pudo iniciar sesión');
            setLoginBusy(false);
            return;
          }
          onLogin('alumno', {
            code: result.student?.code || code,
            mustChangePassword: !!result.must_change_password,
            student: result.student,
          });
        } catch (e) {
          setLoginError(e.message || 'No se pudo validar el alumno');
        }
        setLoginBusy(false);
        return;
      }
      onLogin('alumno', { code });
      return;
    }

    if (!isSupabaseReady()) {
      const st = typeof getSupabaseConfigStatus === 'function' ? getSupabaseConfigStatus() : null;
      setLoginError(st?.message || 'Falta config.js con Supabase. Copia config.example.js a local.settings.js y pega url + anon key.');
      return;
    }
    if (!email.trim() || !password) {
      setLoginError('Ingresa tu correo y contraseña.');
      return;
    }
    setLoginBusy(true);
    try {
      await signInWithEmail(email, password);
      const role = await fetchMyProfileRole();
      if (role !== 'admin') {
        await signOutSupabase();
        setLoginError('La cuenta entró, pero no es administrador. En SQL Editor ejecuta: UPDATE profiles SET role = \'admin\' WHERE email = tu correo;');
        setLoginBusy(false);
        return;
      }
      onLogin('admin');
    } catch (e) {
      setLoginError(loginErrorMessage(e));
    }
    setLoginBusy(false);
  };

  return (
    <>
    <div className="tecos-login-layout" style={{
      minHeight: '100vh', display: 'grid', gridTemplateColumns: '1fr 1fr',
      background: theme.bg, position: 'relative',
    }}>
      {/* Left: branding */}
      <div className="tecos-login-brand" style={{
        position: 'relative', overflow: 'hidden',
        background: `linear-gradient(135deg, ${theme.primary} 0%, ${theme.primaryDark} 100%)`,
        display: 'grid', placeItems: 'center', padding: 60,
      }}>
        <CourtLines color="#fff" opacity={0.2} />
        <div className="tecos-login-vb tecos-login-vb--1" style={{ position: 'absolute', top: '12%', left: '8%' }}>
          <Volleyball size={140} detailed theme={theme} />
        </div>
        <div className="tecos-login-vb tecos-login-vb--2" style={{ position: 'absolute', bottom: '8%', right: '6%' }}>
          <Volleyball size={200} detailed theme={theme} />
        </div>
        <div style={{
          position: 'relative', textAlign: 'center', color: '#fff', zIndex: 2,
          display: 'flex', flexDirection: 'column', alignItems: 'center',
        }}>
          <Logo size={120} withText={false} theme={theme} />
          <h2 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 64, letterSpacing: 2, marginTop: 30, marginBottom: 12, lineHeight: 1, fontWeight: 400 }}>
            BIENVENIDO<br />DE VUELTA
          </h2>
          <p style={{ fontFamily: 'Inter, sans-serif', opacity: 0.85, fontSize: 16, maxWidth: 380 }}>
            Accede a tu portal para ver pagos, eventos, compras y mantenerte conectado con la academia.
          </p>
        </div>
      </div>

      {/* Right: form */}
      <div className="tecos-login-form-col" style={{ display: 'grid', placeItems: 'center', padding: 40, position: 'relative' }}>
        <button onClick={onBack} style={{
          position: 'absolute', top: 24, right: 24,
          background: theme.bgInput, border: `1px solid ${theme.border}`,
          color: theme.text, borderRadius: 8, padding: '8px 14px',
          fontSize: 12, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
          fontFamily: 'Inter, sans-serif',
        }}><Icon name="arrowLeft" size={14} />Volver al sitio</button>

        <div style={{ width: '100%', maxWidth: 420 }}>
          <h3 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 44, color: theme.text, letterSpacing: 1, margin: 0, fontWeight: 400 }}>INICIAR SESIÓN</h3>
          <p style={{ color: theme.textDim, fontSize: 14, marginTop: 6, fontFamily: 'Inter, sans-serif' }}>Selecciona tu tipo de acceso para continuar.</p>

          {/* Mode toggle */}
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4,
            background: theme.bgInput, padding: 4, borderRadius: 10,
            border: `1px solid ${theme.border}`, marginTop: 26, marginBottom: 20,
          }}>
            {[
              { id: 'alumno', l: 'Alumno', icon: 'user' },
              { id: 'admin', l: 'Administrador', icon: 'settings' },
            ].map(m => (
              <button key={m.id} onClick={() => switchMode(m.id)} style={{
                padding: '12px 16px', borderRadius: 8, border: 'none',
                background: mode === m.id ? theme.bgElev : 'transparent',
                color: mode === m.id ? theme.primary : theme.textDim,
                fontSize: 13, fontWeight: 700, letterSpacing: 0.6, cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center',
                fontFamily: 'Inter, sans-serif',
                boxShadow: mode === m.id ? `0 4px 14px ${theme.primaryGlow}` : 'none',
                transition: 'all .2s',
              }}><Icon name={m.icon} size={16} />{m.l}</button>
            ))}
          </div>

          <div style={{ display: 'grid', gap: 14 }}>
            {mode === 'alumno' ? (
              <>
                <div>
                  <label style={{ fontSize: 11, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase' }}>ID alumno</label>
                  <div style={{ display: 'flex', marginTop: 6 }}>
                    <span style={{
                      padding: '12px 14px', background: theme.bgInput, border: `1px solid ${theme.border}`,
                      borderRadius: '8px 0 0 8px', fontFamily: 'Bebas Neue, sans-serif', fontSize: 20, color: theme.primary,
                    }}>TEC</span>
                    <input
                      type="text"
                      value={studentDigits}
                      onChange={e => {
                        const next = e.target.value.replace(/\D/g, '').slice(0, 3);
                        setStudentDigits(next);
                      }}
                      placeholder=""
                      maxLength={3}
                      inputMode="numeric"
                      pattern="[0-9]*"
                      autoComplete="off"
                      autoCorrect="off"
                      spellCheck={false}
                      data-lpignore="true"
                      data-1p-ignore="true"
                      name="tecos-student-id-digits"
                      id="tecos-student-id-digits"
                      style={{
                        flex: 1, padding: 12, border: `1px solid ${theme.border}`, borderLeft: 'none',
                        borderRadius: '0 8px 8px 0', background: theme.bgInput, color: theme.text,
                        fontFamily: 'Bebas Neue, sans-serif', fontSize: 22,
                      }}
                    />
                  </div>
                </div>
                <Input theme={theme} label="Contraseña" type="password" placeholder=""
                  value={studentPassword} onChange={e => setStudentPassword(e.target.value)} icon="settings"
                  autoComplete="new-password" name="tecos-student-password" />
              </>
            ) : (
              <>
                <Input theme={theme} label="Correo administrador" placeholder="" icon="user"
                  value={email} onChange={e => setEmail(e.target.value)} autoComplete="username" />
                <Input theme={theme} label="Contraseña" type="password" placeholder="" icon="settings"
                  value={password} onChange={e => setPassword(e.target.value)} autoComplete="current-password" />
              </>
            )}
            {loginError && <div style={{ color: theme.danger, fontSize: 13, fontFamily: 'Inter, sans-serif', lineHeight: 1.45 }}>{loginError}</div>}
            <Btn theme={theme} size="lg" icon="arrowRight" onClick={handleSubmit} disabled={loginBusy}>
              {loginBusy ? 'Entrando…' : `Entrar como ${mode === 'alumno' ? 'alumno' : 'administrador'}`}
            </Btn>
          </div>

          <div style={{
            marginTop: 30, paddingTop: 20, borderTop: `1px solid ${theme.border}`,
            textAlign: 'center', fontSize: 13, color: theme.textDim, fontFamily: 'Inter, sans-serif',
          }}>
            ¿Aún no eres parte?{' '}
            <a
              onClick={() => setInfoModalOpen(true)}
              style={{ color: theme.primary, fontWeight: 600, cursor: 'pointer' }}
              role="button"
              tabIndex={0}
              onKeyDown={e => { if (e.key === 'Enter') setInfoModalOpen(true); }}
            >
              Solicita información
            </a>
          </div>
        </div>
      </div>
    </div>
    {typeof SolicitaInformacionModal === 'function' && (
      <SolicitaInformacionModal open={infoModalOpen} onClose={() => setInfoModalOpen(false)} theme={theme} />
    )}
    </>
  );
};

Object.assign(window, { TiendaSection, OrderFlow, LoginScreen });
