const { useState, useEffect, useRef, useCallback } = React;

// ============ KONFIGURATION (sættes af mount()) ============
// API_BASE: origin for Railway-appen når formularen kører på en anden side (Shopify-embed).
// EMBEDDED: true når formularen er indlejret som script på omfaun.dk (ikke iframe/standalone).
let API_BASE = '';
let EMBEDDED = false;
let ROOT_EL = null;

// API helper (public endpoints, ingen credentials nødvendige)
const api = {
  get: async (url) => {
    const res = await fetch(API_BASE + url);
    if (!res.ok) { const err = await res.json().catch(() => ({})); throw err; }
    return res.json();
  },
  post: async (url, data) => {
    const res = await fetch(API_BASE + url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
    const json = await res.json().catch(() => ({ error: 'Ukendt fejl' }));
    if (!res.ok) throw json;
    return json;
  }
};

// Konvertering: æg <-> bakker (intern enhed)
const eggsToTrays = (eggs) => eggs / 30;
const traysToEggs = (trays) => trays * 30;

// Formatér æg med bakker i parentes: "90 æg (3 bk.)" eller "15 æg (½ bk.)"
const formatTrays = (trays) => {
  if (trays === 0.5) return '½';
  if (trays % 1 === 0.5) return `${Math.floor(trays)}½`;
  return `${trays}`;
};
const formatEggsWithTrays = (eggs) => {
  const trays = eggsToTrays(eggs);
  return `${eggs} æg (${formatTrays(trays)} bk.)`;
};

// Formatér dato pænt (første bogstav stort, resten som da-DK giver det)
const formatDate = (dateStr) => {
  const date = new Date(dateStr + 'T12:00:00');
  const str = date.toLocaleDateString('da-DK', { weekday: 'long', day: 'numeric', month: 'long' });
  return str.charAt(0).toUpperCase() + str.slice(1);
};

// Formatér afhentningsvindue: "26. – 28. maj"
const formatPickupWindow = (dateStr) => {
  const start = new Date(dateStr + 'T12:00:00');
  const end = new Date(start);
  end.setDate(end.getDate() + 2);
  const sameMonth = start.getMonth() === end.getMonth();
  const startStr = sameMonth
    ? start.getDate() + '.'
    : start.toLocaleDateString('da-DK', { day: 'numeric', month: 'short' });
  const endStr = end.toLocaleDateString('da-DK', { day: 'numeric', month: 'long' });
  return `${startStr} – ${endStr}`;
};

// Oversæt frekvens til dansk
const frequencyLabel = (freq) => {
  const labels = { 'weekly': 'Ugentlig', 'biweekly': 'Hver 2. uge', 'triweekly': 'Hver 3. uge', 'monthly': 'Månedlig' };
  return labels[freq] || freq;
};

// Beregn pris ud fra antal æg
const calculatePrice = (eggs) => {
  // 15 æg = 80 kr, 30 æg = 150 kr
  const fullTrays = Math.floor(eggs / 30);
  const halfTrays = (eggs % 30 >= 15) ? 1 : 0;
  return fullTrays * 150 + halfTrays * 80;
};

// postMessage til parent iframe for dynamisk højde
const notifyParentHeight = () => {
  if (EMBEDDED || window.self === window.top) return;
  try {
    const height = (ROOT_EL || document.getElementById('root')).scrollHeight;
    window.parent.postMessage({ type: 'omfaun-height', height }, '*');
  } catch (e) {}
};

// Return-URL efter MobilePay. I embed-tilstand skal kunden tilbage til den Shopify-side
// formularen ligger på (serveren tilføjer selv payment_reference). Ellers bruger serveren
// sin standard (/bestil.html).
const getReturnUrl = () => {
  if (!EMBEDDED) return undefined;
  try {
    const u = new URL(window.location.href);
    u.searchParams.delete('payment_reference');
    u.hash = '';
    return u.toString();
  } catch (e) { return undefined; }
};

// Opret MobilePay-betaling fra et payment intent
const createPayment = ({ phone, verificationId, intentId }) =>
  api.post('/api/public/payments/create', { phone, verificationId, intentId, returnUrl: getReturnUrl() });

// Validér at en URL er en omfaun.dk-side (bruges til parent-URL fra postMessage/referrer)
const isValidParentUrl = (urlStr) => {
  try {
    const u = new URL(urlStr);
    return u.hostname !== window.location.hostname &&
           (u.hostname === 'omfaun.dk' || u.hostname.endsWith('.omfaun.dk'));
  } catch (e) { return false; }
};

// ============ STEP 1: Telefonnummer ============
function PhoneStep({ onCodeSent }) {
  const [phone, setPhone] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await api.post('/api/public/sms/send-code', { phone });
      onCodeSent(phone);
    } catch (err) {
      setError(err.error || 'Kunne ikke sende kode');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-4">
      <div className="text-center space-y-2">
        <div className="text-4xl">🥚</div>
        <h1 className="text-xl font-bold text-sand-800">Bestil æg</h1>
        <p className="text-sand-500 text-sm">Omfaun Landbrug</p>
      </div>

      <p className="text-sand-600 text-sm text-center">
        Indtast dit telefonnummer - så får du en personlig kode og har altid et overblik over dine bestillinger.
      </p>

      <form onSubmit={handleSubmit} className="space-y-3">
        <div>
          <label className="block text-sm font-medium text-sand-700 mb-1">Telefonnummer</label>
          <input
            type="tel"
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            placeholder="12 34 56 78"
            className="w-full px-3 py-2.5 border border-sand-200 rounded-lg text-base"
            autoFocus
            required
          />
        </div>

        {error && <p className="text-red-600 text-sm">{error}</p>}

        <button
          type="submit"
          disabled={loading || phone.replace(/\D/g, '').length < 8}
          className="w-full py-2.5 bg-sand-800 hover:bg-sand-700 text-white font-medium rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          {loading ? 'Sender...' : 'Modtag kode og bestil æg'}
        </button>
      </form>
    </div>
  );
}

// ============ STEP 2: Bekræft kode ============
function VerifyStep({ phone, onVerified, onBack }) {
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [resendCountdown, setResendCountdown] = useState(60);
  const inputRef = useRef(null);

  useEffect(() => {
    if (resendCountdown > 0) {
      const timer = setTimeout(() => setResendCountdown(resendCountdown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [resendCountdown]);

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  const handleCodeChange = async (value) => {
    const cleaned = value.replace(/\D/g, '').substring(0, 4);
    setCode(cleaned);

    if (cleaned.length === 4) {
      setError('');
      setLoading(true);
      try {
        const result = await api.post('/api/public/sms/verify-code', { phone, code: cleaned, sessionId: funnelSessionId });
        onVerified(result);
      } catch (err) {
        setError(err.error || 'Forkert kode');
        setCode('');
        inputRef.current?.focus();
      } finally {
        setLoading(false);
      }
    }
  };

  const handleResend = async () => {
    setError('');
    try {
      await api.post('/api/public/sms/send-code', { phone });
      setResendCountdown(60);
    } catch (err) {
      setError(err.error || 'Kunne ikke sende ny kode');
    }
  };

  return (
    <div className="space-y-4">
      <button onClick={onBack} className="text-sand-500 hover:text-sand-700 text-sm flex items-center gap-1">
        <span>&larr;</span> Skift nummer
      </button>

      <div className="text-center space-y-2">
        <h2 className="text-lg font-bold text-sand-800">Indtast kode</h2>
        <p className="text-sand-500 text-sm">
          Vi har sendt en 4-cifret kode til<br />
          <span className="font-medium text-sand-700">{phone}</span>
        </p>
      </div>

      <div className="flex justify-center">
        <input
          ref={inputRef}
          type="text"
          inputMode="numeric"
          value={code}
          onChange={(e) => handleCodeChange(e.target.value)}
          placeholder="0000"
          className="w-32 text-center text-2xl tracking-[0.5em] px-3 py-3 border border-sand-200 rounded-lg font-mono"
          maxLength={4}
          autoComplete="one-time-code"
        />
      </div>

      {loading && <p className="text-sand-500 text-sm text-center">Tjekker kode...</p>}
      {error && <p className="text-red-600 text-sm text-center">{error}</p>}

      <div className="text-center">
        {resendCountdown > 0 ? (
          <p className="text-sand-400 text-sm">Send igen om {resendCountdown}s</p>
        ) : (
          <button onClick={handleResend} className="text-yolk-600 hover:text-yolk-700 text-sm font-medium">
            Send ny kode
          </button>
        )}
      </div>
    </div>
  );
}

// Klippekort-pakkedata
const PREPAID_PACKAGES = {
  '10': { trays: 10, price: 1450, label: '10-pakke', perTray: '145,00' },
  '20': { trays: 20, price: 2800, label: '20-pakke', perTray: '140,00' }
};

// ============ STEP 3: Bestilling ============
function OrderStep({ verificationData, phone, onOrderPlaced, parentPageUrl }) {
  const { customer, prepaid, prepaidFutureDeducted = 0, upcomingOrders: initialOrders, verificationId, subscriptions } = verificationData;
  const [orders, setOrders] = useState(initialOrders || []);
  const [skippingOrderId, setSkippingOrderId] = useState(null);
  const [name, setName] = useState(customer?.name || '');
  const deliveryType = 'pickup'; // Online-bestilling tilbyder kun afhentning
  const [pickupLocationId, setPickupLocationId] = useState(customer?.defaultPickupLocation || '');
  const [locations, setLocations] = useState([]);
  const [availableDates, setAvailableDates] = useState([]);
  const [selectedDates, setSelectedDates] = useState({}); // { date: quantity }
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [purchasePrepaid, setPurchasePrepaid] = useState(null); // null, '10', eller '20'
  const [showPrepaidSection, setShowPrepaidSection] = useState(false);
  const [showMoreDates, setShowMoreDates] = useState(false);
  const [editingName, setEditingName] = useState(false);
  const [newName, setNewName] = useState(customer?.name || '');
  const [customerName, setCustomerName] = useState(customer?.name || '');
  const [savingName, setSavingName] = useState(false);

  // Opdel ordrer i abonnements- og manuelle ordrer
  const subscriptionOrders = orders.filter(o => o.subscriptionId);
  const manualOrders = orders.filter(o => !o.subscriptionId && o.status !== 'cancelled');

  // Spring over en abonnements-levering
  const handleSkip = async (orderId) => {
    if (!confirm('Er du sikker på, at du vil springe denne levering over?')) return;
    setSkippingOrderId(orderId);
    try {
      await api.post(`/api/public/orders/${orderId}/skip`, { phone, verificationId });
      setOrders(prev => prev.map(o => o.id === orderId ? { ...o, status: 'cancelled' } : o));
    } catch (err) {
      alert(err.error || 'Kunne ikke springe over');
    } finally {
      setSkippingOrderId(null);
    }
  };

  useEffect(() => {
    Promise.all([
      api.get('/api/public/pickup-locations'),
      api.get('/api/public/available-dates')
    ]).then(([publicLocs, dates]) => {
      // Private fællesadresser (kun dem kunden er tilknyttet) vises øverst
      const privateLocs = verificationData.privateLocations || [];
      const locs = [...privateLocs, ...publicLocs.filter(l => !privateLocs.some(p => p.id === l.id))];
      setLocations(locs);
      setAvailableDates(dates);
      if (locs.length > 0 && !locs.some(l => l.id === pickupLocationId)) {
        setPickupLocationId(locs[0].id);
      }
      setLoading(false);
    }).catch(err => {
      setError('Kunne ikke hente data');
      setLoading(false);
    });
  }, []);

  // Notify parent iframe om højde-ændringer
  useEffect(() => {
    setTimeout(notifyParentHeight, 100);
  }, [availableDates, selectedDates, loading, orders, purchasePrepaid, showPrepaidSection, showMoreDates]);

  // selectedDates holder æg-antal (15, 30, 45...)
  const totalEggs = Object.values(selectedDates).reduce((sum, q) => sum + q, 0);
  // Faktisk tilgængelige klip (som DB ser dem — bruges til prisberegning)
  const existingPrepaidAvailableEggs = traysToEggs(prepaid.reduce((sum, p) => sum + p.traysRemaining, 0));
  // Inkludér nyt klippekort i beregning
  const purchasePrepaidEggs = purchasePrepaid ? traysToEggs(PREPAID_PACKAGES[purchasePrepaid].trays) : 0;
  const totalPrepaidAvailableEggs = existingPrepaidAvailableEggs + purchasePrepaidEggs;
  const prepaidCoversEggs = Math.min(totalEggs, totalPrepaidAvailableEggs);
  const toPayEggs = totalEggs - prepaidCoversEggs;
  const eggPrice = calculatePrice(toPayEggs);
  const prepaidPrice = purchasePrepaid ? PREPAID_PACKAGES[purchasePrepaid].price : 0;
  const totalPrice = eggPrice + prepaidPrice;

  // Vis klippekort-tilbud når der er æg at betale (uden klippekort-køb)
  const showPrepaidOffer = totalEggs > 0 && (totalEggs > existingPrepaidAvailableEggs);

  const canSubmit = totalEggs > 0;

  const handleQuantityChange = (date, quantity) => {
    setSelectedDates(prev => {
      const next = { ...prev };
      if (quantity <= 0) {
        delete next[date];
      } else {
        next[date] = quantity;
      }
      return next;
    });
  };

  const handleSubmit = async () => {
    setError('');
    if (Object.keys(selectedDates).length === 0) {
      setError('Vælg mindst én dato');
      return;
    }
    if (!customer && (!name || name.trim().length === 0)) {
      setError('Indtast dit navn');
      return;
    }
    if (!pickupLocationId) {
      setError('Vælg et afhentningssted');
      return;
    }

    setSubmitting(true);
    try {
      const dates = Object.entries(selectedDates).map(([date, eggs]) => ({ date, quantity: eggsToTrays(eggs) }));
      const result = await api.post('/api/public/orders', {
        phone,
        verificationId,
        name: name.trim(),
        dates,
        deliveryType,
        pickupLocationId,
        purchasePrepaid: purchasePrepaid || undefined,
        parentUrl: parentPageUrl || undefined,
        sessionId: funnelSessionId
      });
      onOrderPlaced(result);
    } catch (err) {
      setError(err.error || 'Kunne ikke oprette bestilling');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return <div className="text-center py-8 text-sand-400">Henter tilgængelige datoer...</div>;
  }

  const statusLabel = (status) => {
    if (status === 'confirmed') return { text: 'Bekræftet', cls: 'bg-green-100 text-green-800' };
    if (status === 'delivered') return { text: 'Leveret', cls: 'bg-sand-100 text-sand-600' };
    return { text: 'Afventer', cls: 'bg-yolk-100 text-yolk-800' };
  };

  const paymentLabel = (paymentStatus, paymentType) => {
    if (paymentStatus === 'paid') {
      if (paymentType === 'prepaid') return { text: '🎫 Klippekort', cls: 'text-yolk-700' };
      return { text: 'Betalt', cls: 'text-green-700' };
    }
    return { text: 'Afventer betaling', cls: 'text-sand-500' };
  };

  const handleSaveName = async () => {
    if (!newName.trim() || newName.trim() === customerName) {
      setEditingName(false);
      return;
    }
    setSavingName(true);
    try {
      await api.post('/api/public/customer/update-name', {
        phone, verificationId, name: newName.trim()
      });
      setCustomerName(newName.trim());
      setEditingName(false);
    } catch (err) {
      // Ignorer fejl, behold gammelt navn
    }
    setSavingName(false);
  };

  return (
    <div className="space-y-5">
      {/* Velkomst */}
      <div className="text-center">
        {!editingName ? (
          <div className="flex items-center justify-center gap-2">
            <h2 className="text-lg font-bold text-sand-800">
              {customer ? `Hej ${customerName}!` : 'Velkommen!'}
            </h2>
            {customer && (
              <button
                onClick={() => { setNewName(customerName); setEditingName(true); }}
                className="text-sand-300 hover:text-sand-500 text-xs"
                title="Ret navn"
              >✏️</button>
            )}
          </div>
        ) : (
          <div className="flex items-center gap-2">
            <input
              type="text"
              value={newName}
              onChange={e => setNewName(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSaveName()}
              className="flex-1 px-3 py-1.5 border border-sand-200 rounded-lg text-sm text-center"
              autoFocus
            />
            <button
              onClick={handleSaveName}
              disabled={savingName}
              className="text-xs text-green-600 hover:text-green-700 font-medium"
            >{savingName ? '...' : 'Gem'}</button>
            <button
              onClick={() => setEditingName(false)}
              className="text-xs text-sand-400 hover:text-sand-600"
            >Annuller</button>
          </div>
        )}
      </div>

      {/* Klippekort-status */}
      {prepaid.length > 0 && (
        <div className="card rounded-lg p-3">
          <div className="flex items-center gap-2">
            <span className="text-lg">🎫</span>
            <div>
              <p className="text-xs font-medium uppercase tracking-wide text-sand-500">Klippekort</p>
              <p className="text-sm text-sand-700">
                Du har <span className="font-bold text-yolk-700">{formatTrays(prepaid.reduce((sum, p) => sum + p.traysRemaining, 0))}</span> bakker tilbage
                {prepaidFutureDeducted > 0 && <span className="text-sand-400 text-xs"> (+{formatTrays(prepaidFutureDeducted)} brugt på fremtidige ordrer)</span>}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Faste bestillinger (abonnementer) */}
      {subscriptions && subscriptions.length > 0 && (
        <div>
          <p className="text-xs font-medium uppercase tracking-wide text-sand-500 mb-2">Dine faste bestillinger</p>
          <div className="space-y-3">
            {subscriptions.map(sub => {
              const subOrders = subscriptionOrders
                .filter(o => o.subscriptionId === sub.id)
                .sort((a, b) => a.date.localeCompare(b.date));
              const locationName = locations.find(l => l.id === sub.pickupLocation)?.name;

              return (
                <div key={sub.id} className="card rounded-lg overflow-hidden">
                  <div className="p-3 bg-sand-50 border-b border-sand-100">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium text-sm text-sand-800">
                          {formatTrays(sub.quantity)} bk. &middot; {frequencyLabel(sub.frequency)}
                        </p>
                        <p className="text-xs text-sand-500 mt-0.5">
                          {sub.deliveryType === 'delivery'
                            ? 'Hjemmelevering'
                            : locationName ? `${locationName}` : 'Afhentning'}
                        </p>
                      </div>
                      {sub.nextDelivery && (
                        <div className="text-right">
                          <p className="text-xs text-sand-400">Næste</p>
                          <p className="text-sm font-medium text-sand-700 ">{formatDate(sub.nextDelivery)}</p>
                        </div>
                      )}
                    </div>
                  </div>
                  {subOrders.length > 0 && (
                    <div className="divide-y divide-sand-100">
                      {subOrders.map(order => {
                        const isSkipped = order.status === 'cancelled';
                        const isSkipping = skippingOrderId === order.id;
                        return (
                          <div key={order.id} className={`flex items-center justify-between p-3 ${isSkipped ? 'opacity-50' : ''}`}>
                            <div>
                              <span className={`text-sm capitalize ${isSkipped ? 'line-through text-sand-400' : 'text-sand-800'}`}>
                                {formatDate(order.date)}
                              </span>
                              <span className="text-sm text-sand-500 ml-2">
                                {formatEggsWithTrays(traysToEggs(order.quantity))}
                              </span>
                            </div>
                            <div>
                              {isSkipped ? (
                                <span className="text-xs text-sand-400 italic">Sprunget over</span>
                              ) : (
                                <button
                                  onClick={() => handleSkip(order.id)}
                                  disabled={isSkipping}
                                  className="text-xs text-sand-500 hover:text-red-600 border border-sand-200 hover:border-red-300 rounded-md px-2 py-1 transition-colors disabled:opacity-50"
                                >
                                  {isSkipping ? '...' : 'Spring over'}
                                </button>
                              )}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Manuelle ordrer (ikke-abonnement) */}
      {manualOrders.length > 0 && (
        <div>
          <p className="text-xs font-medium uppercase tracking-wide text-sand-500 mb-2">Dine kommende ordrer</p>
          <div className="card rounded-lg divide-y divide-sand-100">
            {manualOrders.map(order => {
              const s = statusLabel(order.status);
              const p = paymentLabel(order.paymentStatus, order.paymentType);
              return (
                <div key={order.id} className="flex items-center justify-between p-3">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-sand-800 ">{formatDate(order.date)}</span>
                    <span className={`text-xs px-1.5 py-0.5 rounded-full font-medium ${s.cls}`}>{s.text}</span>
                  </div>
                  <div className="text-right">
                    <span className="text-sm font-medium text-sand-800">{formatEggsWithTrays(traysToEggs(order.quantity))}</span>
                    <span className={`block text-xs ${p.cls}`}>{p.text}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Divider */}
      {(subscriptions?.length > 0 || manualOrders.length > 0) && (
        <div className="border-t border-sand-200 pt-2">
          <p className="text-xs font-medium uppercase tracking-wide text-sand-500">Ny bestilling</p>
        </div>
      )}

      {/* Navn (kun for nye kunder) */}
      {!customer && (
        <div>
          <label className="block text-sm font-medium text-sand-700 mb-1">Dit navn</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Fulde navn"
            className="w-full px-3 py-2.5 border border-sand-200 rounded-lg text-base"
            required
          />
        </div>
      )}

      {/* Afhentningssted */}
      <div>
        <label className="block text-sm font-medium text-sand-700 mb-2">Afhentningssted</label>
        <div className="space-y-2">
          {locations.map(loc => (
            <label
              key={loc.id}
              className={`flex items-center gap-3 p-3 border rounded-lg cursor-pointer transition-colors ${
                pickupLocationId === loc.id
                  ? 'border-yolk-400 bg-yolk-50'
                  : 'border-sand-200 hover:border-sand-300'
              }`}
            >
              <input type="radio" name="pickup" value={loc.id} checked={pickupLocationId === loc.id}
                onChange={() => setPickupLocationId(loc.id)} className="accent-yolk-500" />
              <div>
                <p className="font-medium text-sm text-sand-800">{loc.name}</p>
                {loc.address && <p className="text-xs text-sand-500">{loc.address}</p>}
              </div>
            </label>
          ))}
        </div>
      </div>

      {/* Datoer */}
      <div>
        <label className="block text-sm font-medium text-sand-700 mb-2">Vælg datoer og antal æg</label>
        {deliveryType === 'pickup' && availableDates.length > 0 && (
          <div className="rounded-lg bg-yolk-50/70 border border-yolk-200/70 px-3 py-2 mb-3 flex items-start gap-2">
            <span aria-hidden="true" className="text-base leading-5">📅</span>
            <p className="text-xs text-sand-700 leading-relaxed">
              Vælg en <span className="font-medium">tirsdag</span> — æggene kan afhentes <span className="font-medium">tirsdag, onsdag eller torsdag</span>. Bestilling lukker <span className="font-medium">mandag kl. 12</span>.
            </p>
          </div>
        )}
        {availableDates.length === 0 ? (
          <p className="text-sand-500 text-sm py-4 text-center">Ingen tilgængelige datoer lige nu.</p>
        ) : (
          <div className="space-y-2">
            {availableDates.slice(0, showMoreDates ? 6 : 3).map(({ date, availableTrays, soldOut, closed }) => {
              const eggs = selectedDates[date] || 0;
              const isSelected = eggs > 0;
              const maxEggs = traysToEggs(Math.min(12, availableTrays));
              const atMax = eggs >= maxEggs;
              // Ferielukket eller udsolgt: datoen vises, men kan ikke bestilles
              const unavailable = closed || soldOut;
              const unavailableLabel = closed ? 'Ferielukket' : 'Udsolgt';
              const selectedLocation = deliveryType === 'pickup'
                ? locations.find(l => l.id === pickupLocationId)
                : null;
              const openingHours = selectedLocation?.openingHours;

              return (
                <div
                  key={date}
                  className={`border rounded-lg p-3 transition-colors ${
                    isSelected ? 'border-yolk-400 bg-yolk-50' : unavailable ? 'border-sand-200 bg-sand-50' : 'border-sand-200'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <p className={`font-medium text-sm ${unavailable ? 'text-sand-500' : 'text-sand-800'}`}>{formatDate(date)}</p>
                      {deliveryType === 'pickup' && !unavailable && (
                        <p className="text-xs text-sand-500 mt-0.5">Afhent {formatPickupWindow(date)}</p>
                      )}
                      {openingHours && !unavailable && (
                        <p className="text-xs text-sand-400">kl. {openingHours}</p>
                      )}
                    </div>
                    {unavailable ? (
                      <span className="inline-flex items-center rounded-full bg-sand-200 px-2.5 py-1 text-xs font-semibold text-sand-600">
                        {unavailableLabel}
                      </span>
                    ) : (
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => handleQuantityChange(date, Math.max(0, eggs - 15))}
                        className="w-8 h-8 rounded-full border border-sand-200 text-sand-600 hover:bg-sand-100 flex items-center justify-center text-lg font-medium disabled:opacity-30"
                        disabled={eggs <= 0}
                      >
                        &minus;
                      </button>
                      <span className={`w-12 text-center text-base font-semibold ${isSelected ? 'text-yolk-700' : 'text-sand-400'}`}>
                        {eggs}
                      </span>
                      <button
                        onClick={() => handleQuantityChange(date, Math.min(maxEggs, eggs + 15))}
                        className="w-8 h-8 rounded-full border border-sand-200 text-sand-600 hover:bg-sand-100 flex items-center justify-center text-lg font-medium disabled:opacity-30"
                        disabled={atMax}
                      >
                        +
                      </button>
                    </div>
                    )}
                  </div>
                  {atMax && !unavailable && (
                    <p className="text-xs text-yolk-700 mt-2">Ikke flere æg tilgængelige denne dato (maks. {maxEggs} æg).</p>
                  )}
                </div>
              );
            })}
            {availableDates.length > 3 && (
              <button
                type="button"
                onClick={() => setShowMoreDates(s => !s)}
                className="w-full text-center text-sm text-yolk-600 hover:text-yolk-700 font-medium py-2"
              >
                {showMoreDates ? 'Skjul senere datoer' : 'Vis senere datoer'}
              </button>
            )}
          </div>
        )}
      </div>

      {/* Klippekort-tilbud — kollapserbar */}
      {showPrepaidOffer && !showPrepaidSection && (
        <button
          onClick={() => setShowPrepaidSection(true)}
          className="w-full text-center text-sm text-yolk-600 hover:text-yolk-700 font-medium py-2"
        >
          Spar med klippekort?
        </button>
      )}
      {showPrepaidOffer && showPrepaidSection && (
        <div className="card rounded-lg p-4 space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-lg">🎫</span>
              <div>
                <p className="text-sm font-medium text-sand-800">Spar med et klippekort</p>
                <p className="text-xs text-sand-500">Klippekortet kan bruges til denne og fremtidige bestillinger</p>
              </div>
            </div>
            <button
              onClick={() => { setShowPrepaidSection(false); setPurchasePrepaid(null); }}
              className="text-sand-400 hover:text-sand-600 text-xs flex-shrink-0"
            >
              Skjul
            </button>
          </div>
          <div className="space-y-2">
            {Object.entries(PREPAID_PACKAGES).map(([key, pkg]) => {
              const isSelected = purchasePrepaid === key;
              const savings = (pkg.trays * 150) - pkg.price;
              return (
                <div
                  key={key}
                  onClick={() => setPurchasePrepaid(isSelected ? null : key)}
                  className={`flex items-center gap-3 p-3 border rounded-lg cursor-pointer transition-colors ${
                    isSelected ? 'border-yolk-400 bg-yolk-50' : 'border-sand-200 hover:border-sand-300'
                  }`}
                >
                  <div className={`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${
                    isSelected ? 'border-yolk-500' : 'border-sand-300'
                  }`}>
                    {isSelected && <div className="w-2 h-2 rounded-full bg-yolk-500" />}
                  </div>
                  <div className="flex-1">
                    <div className="flex justify-between items-center">
                      <p className="font-medium text-sm text-sand-800">{pkg.label} ({pkg.trays} bakker)</p>
                      <p className="font-bold text-sm text-sand-800">{pkg.price} kr</p>
                    </div>
                    <p className="text-xs text-yolk-700">Spar {savings} kr ({pkg.perTray} kr/bakke)</p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Opsummering */}
      {totalEggs > 0 && (
        <div className="card rounded-lg p-4 space-y-2">
          <p className="text-xs font-medium uppercase tracking-wide text-sand-500">Opsummering</p>
          {Object.entries(selectedDates).map(([date, eggs]) => (
            <div key={date} className="flex justify-between text-sm text-sand-600">
              <span >{formatDate(date)}</span>
              <span>{formatEggsWithTrays(eggs)}</span>
            </div>
          ))}
          <div className="text-xs text-sand-500 pt-1">
            {`📍 ${locations.find(l => l.id === pickupLocationId)?.name || 'Afhentning'}`}
          </div>
          <div className="border-t border-sand-100 pt-2 mt-2">
            <div className="flex justify-between text-sm font-medium text-sand-800">
              <span>Total</span>
              <span>{formatEggsWithTrays(totalEggs)}</span>
            </div>
            {prepaidCoversEggs > 0 && (
              <div className="flex justify-between text-sm text-yolk-700">
                <span>Klippekort</span>
                <span>&minus;{formatEggsWithTrays(prepaidCoversEggs)}</span>
              </div>
            )}
            {purchasePrepaid && (
              <div className="flex justify-between text-sm text-sand-600">
                <span>🎫 {PREPAID_PACKAGES[purchasePrepaid].label}</span>
                <span>{PREPAID_PACKAGES[purchasePrepaid].price} kr</span>
              </div>
            )}
            {toPayEggs > 0 && !purchasePrepaid && (
              <div className="flex justify-between text-sm text-sand-600">
                <span>Æg ({formatEggsWithTrays(toPayEggs)})</span>
                <span>{eggPrice} kr</span>
              </div>
            )}
            {toPayEggs > 0 && purchasePrepaid && (
              <div className="flex justify-between text-sm text-sand-600">
                <span>Æg (rest)</span>
                <span>{eggPrice} kr</span>
              </div>
            )}
            {totalPrice > 0 && (
              <div className="flex justify-between text-sm font-bold text-sand-800 mt-1 pt-1 border-t border-sand-100">
                <span>At betale med MobilePay</span>
                <span>{totalPrice} kr</span>
              </div>
            )}
            {totalPrice <= 0 && prepaidCoversEggs > 0 && (
              <div className="flex justify-between text-sm font-bold text-green-700 mt-1">
                <span>Dækket af klippekort</span>
                <span>0 kr</span>
              </div>
            )}
          </div>
        </div>
      )}

      {error && <p className="text-red-600 text-sm">{error}</p>}

      <div>
        <button
          onClick={handleSubmit}
          disabled={submitting || !canSubmit}
          className="w-full py-3 bg-sand-800 hover:bg-sand-700 text-white font-semibold rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-base"
        >
          {submitting ? 'Bestiller...' : totalEggs === 0 ? 'Vælg antal' : totalPrice > 0 ? `Bestil og betal ${totalPrice} kr med MobilePay` : `Bestil ${formatEggsWithTrays(totalEggs)}`}
        </button>
      </div>
    </div>
  );
}

// ============ "Tilbage til omfaun.dk" — vises efter ordrebekræftelse hvis parent-URL er kendt ============
function ReturnToParent({ parentUrl }) {
  const [secondsLeft, setSecondsLeft] = useState(8);

  useEffect(() => {
    if (!parentUrl) return;
    if (secondsLeft <= 0) {
      window.location.href = parentUrl;
      return;
    }
    const t = setTimeout(() => setSecondsLeft(s => s - 1), 1000);
    return () => clearTimeout(t);
  }, [secondsLeft, parentUrl]);

  if (!parentUrl) return null;
  return (
    <button
      onClick={() => { window.location.href = parentUrl; }}
      className="w-full py-2.5 bg-sand-800 hover:bg-sand-900 text-white font-medium rounded-lg transition-colors text-sm"
    >
      Tilbage til omfaun.dk {secondsLeft > 0 && <span className="opacity-70 ml-1">({secondsLeft} sek)</span>}
    </button>
  );
}

// ============ STEP 4: Bekræftelse ============
function ConfirmationStep({ result, locations }) {
  const pickupName = locations.find(l => l.id === result.pickupLocationId)?.name || 'Afhentningssted';

  return (
    <div className="text-center space-y-4">
      <div className="text-5xl">✅</div>
      <h2 className="text-xl font-bold text-sand-800">
        {result.totalPrice ? 'Betalt og bestilt!' : 'Bestilling modtaget!'}
      </h2>

      <p className="text-sand-600 text-sm">
        Tak {result.customerName}! Din bestilling er registreret.
      </p>

      <div className="card rounded-lg p-4 text-left space-y-2">
        {result.orders.map((order, idx) => (
          <div key={order.id || idx} className="flex justify-between text-sm text-sand-700">
            <span >{formatDate(order.date)}</span>
            <span className="font-medium">{formatEggsWithTrays(traysToEggs(order.quantity))}
              {order.paymentType === 'prepaid' && <span className="text-yolk-600 ml-1">🎫</span>}
              {order.paymentType === 'mobilepay' && <span className="text-purple-600 ml-1">💳</span>}
            </span>
          </div>
        ))}
      </div>

      {result.prepaidActivated && (
        <div className="card rounded-lg p-3 text-left">
          <div className="flex items-center gap-2">
            <span className="text-lg">🎫</span>
            <div>
              <p className="text-sm font-medium text-yolk-700">
                Klippekort aktiveret! ({result.prepaidActivated.packageType}-pak)
              </p>
              <p className="text-xs text-sand-500">
                {result.prepaidActivated.remaining} bakker tilbage efter denne bestilling
              </p>
            </div>
          </div>
        </div>
      )}

      {result.prepaidUsed && !result.totalPrice && !result.prepaidActivated && (
        <p className="text-sm text-yolk-700">Klippekort er brugt til betaling.</p>
      )}
      {result.prepaidUsed && result.totalPrice > 0 && !result.prepaidActivated && (
        <p className="text-sm text-yolk-700">Klippekort dækkede en del af bestillingen.</p>
      )}
      {result.totalPrice > 0 && (
        <p className="text-sm text-sand-600">
          Betalt {result.totalPrice} kr med MobilePay
          {result.prepaidPrice > 0 && result.eggPrice > 0 && (
            <span className="text-xs text-sand-400 block">
              (klippekort {result.prepaidPrice} kr + æg {result.eggPrice} kr)
            </span>
          )}
        </p>
      )}

      <ReturnToParent parentUrl={result.parentUrl} />

      <button
        onClick={() => window.location.reload()}
        className="w-full py-2.5 border border-sand-300 text-sand-700 hover:bg-sand-100 font-medium rounded-lg transition-colors text-sm"
      >
        Ny bestilling
      </button>
    </div>
  );
}

// ============ STEP 3B: MobilePay betaling ============
function PaymentStep({ orderResult, phone, verificationId, onPaymentComplete, onPaymentFailed }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handlePay = async () => {
    setLoading(true);
    setError('');
    try {
      const result = await createPayment({ phone, verificationId, intentId: orderResult.intentId });
      // Redirect til MobilePay (bryd ud af iframe så 3DS/MobilePay fungerer)
      (window.top || window).location.href = result.redirectUrl;
    } catch (err) {
      setError(err.error || 'Kunne ikke starte MobilePay-betaling');
      setLoading(false);
    }
  };

  return (
    <div className="space-y-5">
      <div className="text-center">
        <h2 className="text-lg font-bold text-sand-800">Betal med MobilePay</h2>
        <p className="text-sand-500 text-sm mt-1">Gennemfør betaling for at bekræfte din bestilling</p>
      </div>

      <div className="card rounded-lg p-4 text-left space-y-2">
        {orderResult.orders.map((order, idx) => (
          <div key={order.id || idx} className="flex justify-between text-sm text-sand-700">
            <span >{formatDate(order.date)}</span>
            <span className="font-medium">
              {formatEggsWithTrays(traysToEggs(order.quantity))}
              {order.paymentType === 'prepaid' && <span className="text-yolk-600 ml-1">🎫</span>}
            </span>
          </div>
        ))}
      </div>

      {orderResult.prepaidUsed && (
        <p className="text-sm text-yolk-700 text-center">Klippekort dækker en del af bestillingen.</p>
      )}

      <div className="card rounded-lg p-4 text-center">
        <p className="text-xs text-sand-400 uppercase tracking-wide mb-1">At betale</p>
        <p className="text-2xl font-bold text-sand-800">{orderResult.totalPrice} kr</p>
        {orderResult.prepaidPrice > 0 && orderResult.eggPrice > 0 && (
          <p className="text-xs text-sand-400 mt-1">
            Klippekort {orderResult.prepaidPrice} kr + æg {orderResult.eggPrice} kr
          </p>
        )}
        {orderResult.prepaidPrice > 0 && orderResult.eggPrice === 0 && (
          <p className="text-xs text-sand-400 mt-1">Klippekort {orderResult.prepaidPurchase}-pak</p>
        )}
      </div>

      {error && <p className="text-red-600 text-sm text-center">{error}</p>}

      <button
        onClick={handlePay}
        disabled={loading}
        className="w-full py-3 text-white font-semibold rounded-lg transition-colors text-sm disabled:opacity-50"
        style={{ backgroundColor: '#5A2D82' }}
      >
        {loading ? 'Åbner MobilePay...' : `Betal ${orderResult.totalPrice} kr med MobilePay`}
      </button>

      <p className="text-xs text-sand-400 text-center">
        Du bliver sendt videre til MobilePay for at godkende betalingen
      </p>
    </div>
  );
}

// ============ STEP: Venter på MobilePay-betaling ============
function PaymentReturnStep({ paymentReference, phone, verificationId, onPaymentComplete, onRetry }) {
  const [status, setStatus] = useState('checking'); // checking, success, failed, retrying
  const [result, setResult] = useState(null);
  const [error, setError] = useState('');

  useEffect(() => {
    let cancelled = false;
    const checkPayment = async () => {
      try {
        const body = { paymentReference };
        if (phone) body.phone = phone;
        if (verificationId) body.verificationId = verificationId;
        const data = await api.post('/api/public/payments/status', body);
        if (cancelled) return;
        if (data.paid) {
          setStatus('success');
          setResult(data);
          // Kort delay før vi viser bekræftelse
          setTimeout(() => onPaymentComplete(data), 1500);
        } else if (data.state === 'ABORTED' || data.state === 'EXPIRED' || data.state === 'TERMINATED') {
          setStatus('failed');
          setError('Betalingen blev ikke gennemført');
        } else {
          // Stadig i gang — poll igen om 2 sekunder
          setTimeout(checkPayment, 2000);
        }
      } catch (err) {
        if (cancelled) return;
        setStatus('failed');
        setError(err.error || 'Kunne ikke tjekke betalingsstatus');
      }
    };
    checkPayment();
    return () => { cancelled = true; };
  }, []);

  if (status === 'checking') {
    return (
      <div className="text-center py-8 space-y-4">
        <div className="text-4xl animate-pulse">💳</div>
        <p className="text-sand-600 text-sm">Tjekker betaling...</p>
      </div>
    );
  }

  if (status === 'success') {
    return (
      <div className="text-center py-8 space-y-4">
        <div className="text-5xl">✅</div>
        <p className="text-sand-800 font-bold text-lg">Betaling modtaget!</p>
      </div>
    );
  }

  const handleRetry = async () => {
    setStatus('retrying');
    try {
      await onRetry();
    } catch (err) {
      setStatus('failed');
      setError('Kunne ikke starte ny betaling');
    }
  };

  if (status === 'retrying') {
    return (
      <div className="text-center py-8 space-y-3">
        <div className="text-4xl animate-pulse">💳</div>
        <p className="text-sand-600 text-sm">Åbner MobilePay...</p>
      </div>
    );
  }

  return (
    <div className="text-center space-y-4">
      <div className="text-5xl">❌</div>
      <h2 className="text-lg font-bold text-sand-800">Betaling ikke gennemført</h2>
      <p className="text-sand-600 text-sm">{error}</p>
      <p className="text-sand-500 text-xs">Du kan prøve at betale igen.</p>
      <button
        onClick={handleRetry}
        className="w-full py-3 text-white font-semibold rounded-lg transition-colors text-sm"
        style={{ backgroundColor: '#5A2D82' }}
      >
        Prøv igen med MobilePay
      </button>
    </div>
  );
}

// ============ SESSION (localStorage, 7 dage) ============
const SESSION_KEY = 'omfaun_session';
const SESSION_DAYS = 7;

const saveSession = (phone, verificationId) => {
  try {
    localStorage.setItem(SESSION_KEY, JSON.stringify({
      phone, verificationId, savedAt: Date.now()
    }));
  } catch (e) {}
};

const loadSession = () => {
  try {
    const raw = localStorage.getItem(SESSION_KEY);
    if (!raw) return null;
    const session = JSON.parse(raw);
    const age = Date.now() - session.savedAt;
    if (age > SESSION_DAYS * 24 * 60 * 60 * 1000) {
      localStorage.removeItem(SESSION_KEY);
      return null;
    }
    return session;
  } catch (e) { return null; }
};

const clearSession = () => {
  try { localStorage.removeItem(SESSION_KEY); } catch (e) {}
};

// Intent storage (til retry efter mislykket MobilePay-betaling)
const INTENT_KEY = 'omfaun_intent';
const saveIntent = (intentId) => {
  try { localStorage.setItem(INTENT_KEY, intentId); } catch (e) {}
};
const loadIntent = () => {
  try { return localStorage.getItem(INTENT_KEY); } catch (e) { return null; }
};
const clearIntent = () => {
  try { localStorage.removeItem(INTENT_KEY); } catch (e) {}
};

// ============ FUNNEL TRACKING ============
const FUNNEL_SESSION_KEY = 'omfaun_funnel_session';
const getFunnelSessionId = () => {
  try {
    let sid = sessionStorage.getItem(FUNNEL_SESSION_KEY);
    if (!sid) {
      sid = 'fs_' + Math.random().toString(36).substring(2, 10) + Date.now().toString(36);
      sessionStorage.setItem(FUNNEL_SESSION_KEY, sid);
    }
    return sid;
  } catch (e) { return null; }
};

const funnelSessionId = getFunnelSessionId();

// ============ MAIN APP ============
function App() {
  const [step, setStep] = useState('loading'); // loading, phone, verify, order, payment, payment_return, done
  const [phone, setPhone] = useState('');
  const [verificationData, setVerificationData] = useState(null);
  const [orderResult, setOrderResult] = useState(null);
  const [paymentReference, setPaymentReference] = useState(null);
  const [locations, setLocations] = useState([]);
  const [parentPageUrl, setParentPageUrl] = useState(null);

  // Hent locations tidligt
  useEffect(() => {
    api.get('/api/public/pickup-locations').then(setLocations).catch(() => {});
  }, []);

  // postMessage-handshake med parent (omfaun.dk-siden) for at få fat i dens URL.
  // Bruges til at sende brugeren tilbage til oprindelig side efter MobilePay-betaling.
  useEffect(() => {
    // I embed-tilstand ligger formularen allerede på omfaun.dk — ingen parent at vende tilbage til
    if (EMBEDDED || window.self === window.top) return;
    const handler = (e) => {
      if (e.data && e.data.type === 'omfaun-parent-url' && typeof e.data.url === 'string') {
        if (isValidParentUrl(e.data.url)) {
          setParentPageUrl(e.data.url);
        }
      }
    };
    window.addEventListener('message', handler);
    // Bed parent om at sende sin URL (parent svarer via dens message-listener)
    try { window.parent.postMessage({ type: 'omfaun-ready' }, '*'); } catch (e) {}
    return () => window.removeEventListener('message', handler);
  }, []);

  // Prøv at genoptage session ved opstart — tjek også for MobilePay return
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const payRef = params.get('payment_reference');

    // Fjern payment_reference fra URL'en uden reload (bevar øvrige parametre, fx på en Shopify-side)
    if (payRef) {
      try {
        const u = new URL(window.location.href);
        u.searchParams.delete('payment_reference');
        window.history.replaceState({}, '', u.toString());
      } catch (e) {
        window.history.replaceState({}, '', window.location.pathname);
      }
    }

    const session = loadSession();
    if (session) {
      api.post('/api/public/sms/restore-session', {
        phone: session.phone,
        verificationId: session.verificationId,
        sessionId: funnelSessionId
      }).then(data => {
        setPhone(session.phone);
        setVerificationData(data);
        // Hvis vi kommer fra MobilePay-redirect, tjek betaling
        if (payRef) {
          setPaymentReference(payRef);
          setStep('payment_return');
        } else {
          setStep('order');
        }
      }).catch(() => {
        clearSession();
        // Hvis vi har en payment_reference, kan vi stadig vise ordrebekræftelsen
        // (Safari/Firefox ITP rydder iframe-localStorage så sessionen er væk efter MobilePay-redirect)
        if (payRef) {
          setPaymentReference(payRef);
          setStep('payment_return');
        } else {
          setStep('phone');
        }
      });
    } else if (payRef) {
      // Ingen session, men vi har en payment_reference — vis ordrebekræftelse uden session
      setPaymentReference(payRef);
      setStep('payment_return');
    } else {
      setStep('phone');
    }
  }, []);

  // Notify parent om højde ved step-skift
  useEffect(() => {
    setTimeout(notifyParentHeight, 200);
  }, [step]);

  const handleVerified = (data) => {
    saveSession(phone, data.verificationId);
    setVerificationData(data);
    setStep('order');
  };

  const handleLogout = () => {
    clearSession();
    setPhone('');
    setVerificationData(null);
    setStep('phone');
  };

  return (
    <div className={EMBEDDED
      ? 'flex items-start justify-center'
      : 'min-h-screen bg-sand-50 flex items-start justify-center p-4'}>
      <div className="w-full max-w-md">
        <div className={EMBEDDED ? 'card rounded-xl p-5' : 'card rounded-xl p-5 my-4'}>
          {step === 'loading' && (
            <div className="text-center py-8 text-sand-400">Indlæser...</div>
          )}

          {step === 'phone' && (
            <PhoneStep
              onCodeSent={(ph) => {
                setPhone(ph);
                setStep('verify');
              }}
            />
          )}

          {step === 'verify' && (
            <VerifyStep
              phone={phone}
              onVerified={handleVerified}
              onBack={() => setStep('phone')}
            />
          )}

          {step === 'order' && verificationData && (
            <OrderStep
              verificationData={verificationData}
              phone={phone}
              parentPageUrl={parentPageUrl}
              onOrderPlaced={async (result) => {
                setOrderResult(result);
                if (result.paymentRequired) {
                  // Gem intentId til evt. retry efter MobilePay-redirect
                  saveIntent(result.intentId);
                  // Gå direkte til MobilePay uden mellemtrin
                  setStep('redirecting');
                  try {
                    const payResult = await createPayment({
                      phone,
                      verificationId: verificationData.verificationId,
                      intentId: result.intentId
                    });
                    (window.top || window).location.href = payResult.redirectUrl;
                  } catch (err) {
                    setOrderResult(result);
                    setStep('payment');
                  }
                } else {
                  clearIntent();
                  setStep('done');
                }
              }}
            />
          )}

          {step === 'redirecting' && (
            <div className="text-center py-8 space-y-3">
              <div className="text-4xl animate-pulse">💳</div>
              <p className="text-sand-600 text-sm">Åbner MobilePay...</p>
            </div>
          )}

          {step === 'payment' && orderResult && verificationData && (
            <PaymentStep
              orderResult={orderResult}
              phone={phone}
              verificationId={verificationData.verificationId}
              onPaymentComplete={(data) => {
                clearIntent();
                setOrderResult(data);
                setStep('done');
              }}
              onPaymentFailed={() => setStep('payment')}
            />
          )}

          {step === 'payment_return' && paymentReference && (
            <PaymentReturnStep
              paymentReference={paymentReference}
              phone={phone || null}
              verificationId={verificationData ? verificationData.verificationId : null}
              onPaymentComplete={(data) => {
                clearIntent();
                setOrderResult(data);
                setStep('done');
              }}
              onRetry={async () => {
                // Brug gemt intentId til at oprette ny MobilePay-betaling
                const intentId = loadIntent();
                if (!intentId) throw new Error('Ingen bestilling fundet');
                const result = await createPayment({
                  phone,
                  verificationId: verificationData.verificationId,
                  intentId
                });
                (window.top || window).location.href = result.redirectUrl;
              }}
            />
          )}

          {step === 'done' && orderResult && (
            <ConfirmationStep result={orderResult} locations={[...(verificationData?.privateLocations || []), ...locations]} />
          )}
        </div>

        {(step === 'order' || step === 'payment') && (
          <div className="text-center pb-2">
            <button onClick={handleLogout} className="text-sand-400 hover:text-sand-600 text-xs">
              Log ud
            </button>
          </div>
        )}

        <p className="text-center text-xs text-sand-400 pb-4">
          Omfaun Landbrug &middot; Græsæg
          <br />
          <a href="https://omfaun.dk/pages/salgsbetingelser" target="_blank" rel="noopener noreferrer" className="underline hover:text-sand-600">Salgsbetingelser</a>
        </p>
      </div>
    </div>
  );
}

// ============ MOUNT ============
// Bruges både af /bestil.html (standalone/iframe) og af Shopify-embed'et (/embed/bestil.js).
//   opts.apiBase  — origin for appen, fx "https://eggapp.up.railway.app" (tom = samme origin)
//   opts.embedded — true når formularen ligger direkte på en omfaun.dk-side (Shadow DOM)
function mount(rootEl, opts) {
  opts = opts || {};
  API_BASE = (opts.apiBase || '').replace(/\/+$/, '');
  EMBEDDED = !!opts.embedded;
  ROOT_EL = rootEl;

  // Log page_view ved opstart (fire-and-forget)
  if (funnelSessionId) {
    api.post('/api/public/funnel-event', { event: 'page_view', sessionId: funnelSessionId }).catch(() => {});
  }

  ReactDOM.createRoot(rootEl).render(<App />);
}

window.OmfaunBestil = { mount };

// Standalone (/bestil.html): auto-mount på #root
const standaloneRoot = document.getElementById('root');
if (standaloneRoot && standaloneRoot.dataset.omfaunAutoMount === 'true') {
  mount(standaloneRoot, { apiBase: '', embedded: false });
}
