/* CRUD modals for products, experiences, gift cards */
const { useState: pmS } = React;

// ---------- Generic field helpers ----------
function ModalShell({ title, sub, onClose, onSave, saveLabel = 'Gem', children, width = 540, danger }) {
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{width}} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h3>{title}</h3>
          {sub && <p>{sub}</p>}
        </div>
        <div className="modal-body" style={{maxHeight: 'calc(100vh - 240px)', overflow: 'auto'}}>
          {children}
        </div>
        <div className="modal-foot">
          {danger && <button className="btn btn-ghost" style={{color: 'var(--danger)', marginRight: 'auto', borderColor: 'rgba(224,83,58,0.3)'}} onClick={danger.onClick}><Icon name="x" size={14}/> {danger.label}</button>}
          <button className="btn btn-ghost" onClick={onClose}>Annuller</button>
          <button className="btn btn-accent" onClick={onSave}><Icon name="check" size={14}/> {saveLabel}</button>
        </div>
      </div>
    </div>
  );
}

// ---------- Experience editor ----------
function ExperienceModal({ initial, items = [], onSave, onClose, onDelete }) {
  const [name, setName] = pmS(initial?.name || '');
  const [desc, setDesc] = pmS(initial?.desc || '');
  const [price, setPrice] = pmS(initial?.price || '');
  const [dur, setDur] = pmS(initial?.dur || '105m');
  const [tag, setTag] = pmS(initial?.tag || 'Standard');
  const [active, setActive] = pmS(initial?.active !== false);
  const [includedItems, setIncludedItems] = pmS(initial?.items || []);
  const isNew = !initial;

  const toggleItem = (n) =>
    setIncludedItems(prev => prev.includes(n) ? prev.filter(x => x !== n) : [...prev, n]);
  const includedTotal = items
    .filter(it => includedItems.includes(it.name))
    .reduce((a, it) => a + (it.price || 0), 0);

  return (
    <ModalShell
      title={isNew ? 'NY OPLEVELSE' : 'REDIGER OPLEVELSE'}
      sub="Definér hvordan oplevelsen vises og bookes online"
      onClose={onClose}
      onSave={() => { if (!name) return alert('Indtast navn'); onSave({ name, desc, price, dur, tag, active, items: includedItems, covers: initial?.covers || 0 }); }}
      danger={!isNew ? { label: 'Slet oplevelse', onClick: () => { onDelete(); onClose(); } } : null}>
      <div className="field"><label>Navn</label><input value={name} onChange={e => setName(e.target.value)} placeholder="f.eks. Smagsmenu (5 retter)"/></div>
      <div className="field"><label>Beskrivelse</label><textarea rows={2} value={desc} onChange={e => setDesc(e.target.value)} placeholder="Vises i booking-flowet"/></div>
      <div style={{display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 12}}>
        <div className="field"><label>Pris</label><input value={price} onChange={e => setPrice(e.target.value)} placeholder="850 kr / pers eller 'Fri'"/></div>
        <div className="field"><label>Varighed</label>
          <select value={dur} onChange={e => setDur(e.target.value)}>
            {['60m','75m','90m','105m','120m','150m','180m','210m','240m'].map(d => <option key={d}>{d}</option>)}
          </select>
        </div>
        <div className="field"><label>Type</label>
          <select value={tag} onChange={e => setTag(e.target.value)}>
            {['Standard','Tasting','Brunch','Privat','Event'].map(d => <option key={d}>{d}</option>)}
          </select>
        </div>
      </div>
      <div className="field">
        <label>Tilknøjne items / retter ({includedItems.length} valgt{includedTotal > 0 ? ` · ${includedTotal} kr i alt` : ''})</label>
        {items.length === 0 ? (
          <div style={{fontSize: 13, color: 'var(--muted)', padding: 12, background: 'var(--surface-2)', borderRadius: 8}}>
            Du har ingen items endnu. Opret retter under fanen „Items“ først.
          </div>
        ) : (
          <div style={{display: 'flex', flexDirection: 'column', gap: 4, maxHeight: 220, overflow: 'auto', padding: 4, background: 'var(--surface-2)', borderRadius: 8}}>
            {items.map(it => {
              const on = includedItems.includes(it.name);
              return (
                <button key={it.name}
                  onClick={() => toggleItem(it.name)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '8px 10px', borderRadius: 6,
                    background: on ? 'var(--ink)' : 'transparent',
                    color: on ? 'var(--bg)' : 'var(--ink)',
                    textAlign: 'left',
                  }}>
                  <span style={{width: 16, height: 16, borderRadius: 4, border: `1.5px solid ${on ? 'var(--bg)' : 'var(--line-strong)'}`, background: on ? 'var(--bg)' : 'transparent', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0}}>
                    {on && <Icon name="check" size={10} stroke={3}/>}
                  </span>
                  <span style={{flex: 1, fontSize: 13}}>{it.name}</span>
                  <span style={{fontSize: 12, opacity: 0.7, fontVariantNumeric: 'tabular-nums'}}>{it.price} kr</span>
                </button>
              );
            })}
          </div>
        )}
      </div>

      <div className="field">
        <label>Status</label>
        <div style={{display: 'flex', gap: 6}}>
          <button className={`chip ${active ? 'active' : ''}`} onClick={() => setActive(true)}>Aktiv</button>
          <button className={`chip ${!active ? 'active' : ''}`} onClick={() => setActive(false)}>Inaktiv</button>
        </div>
      </div>
    </ModalShell>
  );
}

// ---------- Item editor (a dish or product with name + price) ----------
function ItemModal({ initial, onSave, onClose, onDelete }) {
  const [name, setName] = pmS(initial?.name || '');
  const [price, setPrice] = pmS(initial?.price ?? '');
  const isNew = !initial;

  return (
    <ModalShell
      title={isNew ? 'NYT ITEM' : 'REDIGER ITEM'}
      sub="En ret eller et produkt med navn og pris"
      onClose={onClose}
      onSave={() => { if (!name) return alert('Indtast navn'); onSave({ name, price: +price || 0 }); }}
      danger={!isNew ? { label: 'Slet item', onClick: () => { onDelete(); onClose(); } } : null}>
      <div className="field"><label>Navn</label><input value={name} onChange={e => setName(e.target.value)} placeholder="f.eks. Tatar af oksefilet"/></div>
      <div className="field"><label>Pris (kr)</label><input type="number" value={price} onChange={e => setPrice(e.target.value)} placeholder="165"/></div>
    </ModalShell>
  );
}

// ---------- Supplement editor ----------
function SupplementModal({ initial, onSave, onClose, onDelete }) {
  const [n, setN] = pmS(initial?.n || '');
  const [p, setP] = pmS(initial?.p || 0);
  const isNew = !initial;
  return (
    <ModalShell
      title={isNew ? 'NYT TILKØB' : 'REDIGER TILKØB'}
      sub="Valgfrit tilkøb gæsten kan vælge ved booking"
      onClose={onClose}
      onSave={() => { if (!n) return alert('Indtast navn'); onSave({ n, p: +p, sold: initial?.sold || 0 }); }}
      danger={!isNew ? { label: 'Slet', onClick: () => { onDelete(); onClose(); } } : null}>
      <div className="field"><label>Navn</label><input value={n} onChange={e => setN(e.target.value)} placeholder="f.eks. Welcome bobler (glas)"/></div>
      <div className="field"><label>Pris (kr)</label><input type="number" value={p} onChange={e => setP(e.target.value)} placeholder="95"/></div>
    </ModalShell>
  );
}

// ---------- Gift card product editor ----------
function GiftProductModal({ initial, onSave, onClose, onDelete }) {
  const [name, setName] = pmS(initial?.name || '');
  const [amount, setAmount] = pmS(initial?.amount === null ? '' : (initial?.amount || ''));
  const [desc, setDesc] = pmS(initial?.desc || '');
  const [freeAmount, setFreeAmount] = pmS(initial ? initial.amount === null : false);
  const isNew = !initial;

  return (
    <ModalShell
      title={isNew ? 'NYT GAVEKORT' : 'REDIGER GAVEKORT'}
      sub="Tilføj et gavekort gæsterne kan købe online"
      onClose={onClose}
      onSave={() => {
        if (!name) return alert('Indtast navn');
        onSave({ name, amount: freeAmount ? null : +amount, desc, img: initial?.img || 'cash' });
      }}
      danger={!isNew ? { label: 'Slet', onClick: () => { onDelete(); onClose(); } } : null}>
      <div className="field"><label>Navn på gavekort</label><input value={name} onChange={e => setName(e.target.value)} placeholder="f.eks. Smagsmenu for 2"/></div>
      <div className="field"><label>Beskrivelse</label><textarea rows={2} value={desc} onChange={e => setDesc(e.target.value)} placeholder="Hvad indeholder gavekortet"/></div>
      <div className="field">
        <label>Beløb</label>
        <div style={{display: 'flex', gap: 6, marginBottom: 8}}>
          <button className={`chip ${!freeAmount ? 'active' : ''}`} onClick={() => setFreeAmount(false)}>Fast beløb</button>
          <button className={`chip ${freeAmount ? 'active' : ''}`} onClick={() => setFreeAmount(true)}>Frit beløb (køber vælger)</button>
        </div>
        {!freeAmount && (
          <input type="number" value={amount} onChange={e => setAmount(e.target.value)} placeholder="f.eks. 1800"/>
        )}
      </div>

      {name && (
        <div style={{marginTop: 14}}>
          <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700, marginBottom: 6}}>Forhåndsvisning</div>
          <div className="gift-cover" style={{borderRadius: 12, maxWidth: 260}}>
            <div className="gift-monogram">HJEM</div>
            <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 14, letterSpacing: '0.08em'}}>GAVEKORT</div>
            <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 32, letterSpacing: '-0.02em', marginTop: 8}}>
              {freeAmount ? '— kr' : `${amount || 0} kr`}
            </div>
          </div>
        </div>
      )}
    </ModalShell>
  );
}

// ---------- Gift card SALE flow ----------
function GiftSaleModal({ products, onSale, onClose }) {
  const [step, setStep] = pmS(1);
  const [productId, setProductId] = pmS(products[0]?.name);
  const [customAmount, setCustomAmount] = pmS(500);
  const [buyer, setBuyer] = pmS({ name: '', email: '' });
  const [recipient, setRecipient] = pmS({ name: '', email: '' });
  const [message, setMessage] = pmS('');
  const [sendDate, setSendDate] = pmS('today');
  const [paid, setPaid] = pmS(false);

  const product = products.find(p => p.name === productId);
  const amount = product?.amount === null ? +customAmount : product?.amount;

  const submit = () => {
    const code = 'HJ-' + Math.random().toString(36).slice(2, 6).toUpperCase();
    onSale({
      code, buyer: buyer.name, recipient: recipient.name,
      amount, remaining: amount,
      status: 'aktivt', expires: '18/05/2027', message,
    });
    setPaid(true);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{width: 680}} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h3>{paid ? 'GAVEKORT SOLGT' : 'SÆLG GAVEKORT'}</h3>
          {!paid && <p>Trin {step} af 3 · {step === 1 ? 'vælg gavekort' : step === 2 ? 'modtager og hilsen' : 'betal & send'}</p>}
        </div>

        {!paid && (
          <div className="step-indicator">
            <div className={`step-pill ${step >= 1 ? 'done' : ''}`}>1 PRODUKT</div>
            <div className={`step-pill ${step >= 2 ? 'done' : ''}`}>2 MODTAGER</div>
            <div className={`step-pill ${step >= 3 ? 'done' : ''}`}>3 BETALING</div>
          </div>
        )}

        <div className="modal-body" style={{maxHeight: 'calc(100vh - 280px)', overflow: 'auto'}}>
          {paid && (
            <div style={{textAlign: 'center', padding: '20px 0'}}>
              <div style={{width: 64, height: 64, borderRadius: 100, background: 'var(--accent)', color: 'var(--accent-ink)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14}}>
                <Icon name="check" size={28} stroke={3}/>
              </div>
              <h2 style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 28, letterSpacing: '-0.03em', margin: 0}}>SENDT!</h2>
              <p style={{color: 'var(--muted)', maxWidth: 380, margin: '8px auto 0'}}>Gavekortet er sendt til {recipient.email || 'modtageren'}. En kvittering er sendt til {buyer.email}.</p>

              <div className="gift-cover" style={{borderRadius: 14, maxWidth: 280, margin: '22px auto'}}>
                <div className="gift-monogram">HJEM</div>
                <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 14, letterSpacing: '0.08em'}}>GAVEKORT</div>
                <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 36, letterSpacing: '-0.02em', marginTop: 8}}>{amount} kr</div>
                <div style={{fontSize: 11, color: 'var(--muted-2)', marginTop: 12, fontFamily: 'var(--mono)'}}>Til: {recipient.name || 'Modtager'}</div>
              </div>
            </div>
          )}

          {!paid && step === 1 && (
            <>
              <div className="field">
                <label>Hvilket gavekort?</label>
                <div style={{display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10}}>
                  {products.map(p => (
                    <button key={p.name}
                      className={`product-pick ${productId === p.name ? 'active' : ''}`}
                      onClick={() => setProductId(p.name)}>
                      <div style={{fontWeight: 700, fontSize: 14}}>{p.name}</div>
                      <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 22, marginTop: 4}}>{p.amount === null ? 'Frit beløb' : `${p.amount} kr`}</div>
                      <div style={{fontSize: 11, color: 'var(--muted)', marginTop: 4}}>{p.desc}</div>
                    </button>
                  ))}
                </div>
              </div>
              {product?.amount === null && (
                <div className="field">
                  <label>Beløb (kr)</label>
                  <input type="number" value={customAmount} onChange={e => setCustomAmount(e.target.value)} min={100} step={100}/>
                </div>
              )}
            </>
          )}

          {!paid && step === 2 && (
            <>
              <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14}}>
                <div>
                  <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700, marginBottom: 10}}>Køber</div>
                  <div className="field"><label>Navn</label><input value={buyer.name} onChange={e => setBuyer({...buyer, name: e.target.value})}/></div>
                  <div className="field"><label>Email til kvittering</label><input type="email" value={buyer.email} onChange={e => setBuyer({...buyer, email: e.target.value})}/></div>
                </div>
                <div>
                  <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700, marginBottom: 10}}>Modtager</div>
                  <div className="field"><label>Navn på modtager</label><input value={recipient.name} onChange={e => setRecipient({...recipient, name: e.target.value})}/></div>
                  <div className="field"><label>Modtagerens email</label><input type="email" value={recipient.email} onChange={e => setRecipient({...recipient, email: e.target.value})}/></div>
                </div>
              </div>
              <div className="field"><label>Hilsen (vises på gavekortet)</label><textarea rows={3} value={message} onChange={e => setMessage(e.target.value)} placeholder="Tillykke med fødselsdagen!"/></div>
              <div className="field">
                <label>Send</label>
                <div style={{display: 'flex', gap: 6}}>
                  <button className={`chip ${sendDate === 'today' ? 'active' : ''}`} onClick={() => setSendDate('today')}>Med det samme</button>
                  <button className={`chip ${sendDate === 'pick' ? 'active' : ''}`} onClick={() => setSendDate('pick')}>Vælg dato</button>
                </div>
                {sendDate === 'pick' && <input type="date" style={{marginTop: 8}}/>}
              </div>
            </>
          )}

          {!paid && step === 3 && (
            <>
              <div style={{background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 12, padding: 18}}>
                <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700, marginBottom: 10}}>Bestilling</div>
                <div style={{display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--line)'}}>
                  <span>{product?.name}</span><span style={{fontWeight: 700, fontVariantNumeric: 'tabular-nums'}}>{amount} kr</span>
                </div>
                <div style={{display: 'flex', justifyContent: 'space-between', padding: '8px 0', color: 'var(--muted)', fontSize: 12}}>
                  <span>Behandlingsgebyr (Stripe)</span><span style={{fontVariantNumeric: 'tabular-nums'}}>{(amount * 0.014 + 1.8).toFixed(2)} kr</span>
                </div>
                <div style={{display: 'flex', justifyContent: 'space-between', padding: '12px 0 4px', fontFamily: 'var(--display)', fontWeight: 800, fontSize: 22, letterSpacing: '-0.02em'}}>
                  <span>I alt at betale</span><span style={{fontVariantNumeric: 'tabular-nums'}}>{amount} kr</span>
                </div>
              </div>
              <div className="field" style={{marginTop: 14}}>
                <label>Betalingsmetode</label>
                <div style={{display: 'flex', gap: 6}}>
                  <button className="chip active">Kort (Stripe)</button>
                  <button className="chip">MobilePay</button>
                  <button className="chip">Kontant / faktura</button>
                </div>
              </div>
            </>
          )}
        </div>

        <div className="modal-foot">
          {paid ? (
            <>
              <button className="btn btn-ghost" style={{marginRight: 'auto'}}><Icon name="mail" size={14}/> Send igen</button>
              <button className="btn btn-accent" onClick={onClose}>Færdig</button>
            </>
          ) : (
            <>
              <button className="btn btn-ghost" onClick={onClose}>Annuller</button>
              {step > 1 && <button className="btn btn-soft" onClick={() => setStep(step - 1)}><Icon name="chev-left" size={14}/> Tilbage</button>}
              {step < 3 && <button className="btn btn-primary" onClick={() => {
                if (step === 2 && (!buyer.email || !recipient.name)) return alert('Udfyld køber-email og modtager-navn');
                setStep(step + 1);
              }}>Videre <Icon name="chev-right" size={14}/></button>}
              {step === 3 && <button className="btn btn-accent" onClick={submit}><Icon name="check" size={14}/> Bekræft & send</button>}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ExperienceModal, ItemModal, SupplementModal, GiftProductModal, GiftSaleModal });
