// Modals: New Order, QR Code, Delete Confirm

const { useState: useStateModal, useEffect: useEffectModal, useRef } = React;

// ── New Order Modal ──────────────────────────────────────────
function NewOrderModal({ open, onClose, onCreate }) {
  const [form, setForm] = useStateModal({ customerName: '', deceased: '', email: '', phone: '', note: '' });
  const [errors, setErrors] = useStateModal({});
  const [loading, setLoading] = useStateModal(false);

  useEffectModal(() => {
    if (open) { setForm({ customerName: '', deceased: '', email: '', phone: '', note: '' }); setErrors({}); }
  }, [open]);

  if (!open) return null;

  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.customerName.trim()) errs.customerName = 'Bitte Namen angeben';
    if (!form.email.trim()) errs.email = 'Bitte E-Mail angeben';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errs.email = 'Ungültige E-Mail';
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setLoading(true);
    await onCreate(form);
    setLoading(false);
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-header">
          <h2>Neuer Auftrag</h2>
          <p>Die Familie erhält automatisch einen sicheren Upload-Link per E-Mail.</p>
        </div>
        <form onSubmit={submit}>
          <div className="form-group">
            <label>Name der Familie / Ansprechpartner *</label>
            <input className="form-input" type="text" placeholder="z.B. Familie Müller"
              value={form.customerName} onChange={set('customerName')} autoFocus />
            {errors.customerName && <div className="form-hint" style={{ color: 'var(--a-error)' }}>{errors.customerName}</div>}
          </div>
          <div className="form-group">
            <label>Name des Verstorbenen</label>
            <input className="form-input" type="text" placeholder="z.B. Elisabeth Müller"
              value={form.deceased} onChange={set('deceased')} />
          </div>
          <div className="form-group">
            <label>E-Mail-Adresse *</label>
            <input className="form-input" type="email" placeholder="familie@email.de"
              value={form.email} onChange={set('email')} />
            {errors.email && <div className="form-hint" style={{ color: 'var(--a-error)' }}>{errors.email}</div>}
          </div>
          <div className="form-group">
            <label>Telefon <span style={{ fontWeight: 400, color: 'var(--a-muted)' }}>(optional)</span></label>
            <input className="form-input" type="tel" placeholder="+49 …"
              value={form.phone} onChange={set('phone')} />
          </div>
          <div className="form-group">
            <label>Interne Notiz <span style={{ fontWeight: 400, color: 'var(--a-muted)' }}>(optional)</span></label>
            <textarea className="form-textarea" placeholder="Besonderheiten, Termine, Hinweise …"
              value={form.note} onChange={set('note')} rows={3} />
          </div>
          <div className="modal-actions">
            <button type="button" className="btn btn-ghost" onClick={onClose} disabled={loading}>Abbrechen</button>
            <button type="submit" className="btn btn-primary" disabled={loading}>
              <window.Icon.Mail /> {loading ? 'Wird erstellt …' : 'Auftrag erstellen & E-Mail senden'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Real QR Code ─────────────────────────────────────────────
function RealQR({ url }) {
  const ref = useRef(null);
  useEffectModal(() => {
    if (!ref.current || !url) return;
    // Remove all child nodes safely
    while (ref.current.firstChild) ref.current.removeChild(ref.current.firstChild);
    new QRCode(ref.current, {
      text: url,
      width: 220,
      height: 220,
      colorDark: '#2B2419',
      colorLight: '#FFFBF2',
      correctLevel: QRCode.CorrectLevel.M,
    });
  }, [url]);
  return <div ref={ref} style={{ display: 'inline-block' }} />;
}

// ── QR Modal ─────────────────────────────────────────────────
function QRModal({ open, order, onClose, onCopy }) {
  if (!open || !order) return null;
  const url = window.location.origin + '/upload/' + order.token;
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal qr-modal" onClick={e => e.stopPropagation()}>
        <div className="modal-header" style={{ textAlign: 'center', marginBottom: '0.5rem' }}>
          <h2>Upload-Link</h2>
          <p>Scannen oder Link teilen — die Familie kann direkt Fotos hochladen.</p>
        </div>
        <div className="qr-wrapper" style={{ textAlign: 'center', padding: '1rem' }}>
          <RealQR url={url} />
        </div>
        <div className="qr-url" style={{ textAlign: 'center', marginBottom: '0.75rem', wordBreak: 'break-all', fontSize: '0.78rem' }}>{url}</div>
        <div style={{ display: 'flex', gap: '0.5rem', justifyContent: 'center' }}>
          <button className="btn btn-secondary" onClick={() => onCopy(url)}>
            <window.Icon.Copy /> Link kopieren
          </button>
          <button className="btn btn-primary" onClick={onClose}>Fertig</button>
        </div>
      </div>
    </div>
  );
}

// ── Confirm Modal ────────────────────────────────────────────
function ConfirmModal({ open, title, message, confirmLabel = 'Bestätigen', danger = false, onClose, onConfirm }) {
  if (!open) return null;
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 420 }} onClick={e => e.stopPropagation()}>
        <div className="modal-header">
          <h2>{title}</h2>
          <p>{message}</p>
        </div>
        <div className="modal-actions" style={{ borderTop: 'none', paddingTop: 0, marginTop: '1rem' }}>
          <button className="btn btn-ghost" onClick={onClose}>Abbrechen</button>
          <button className={`btn ${danger ? 'btn-danger' : 'btn-primary'}`} onClick={onConfirm}>
            {confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { NewOrderModal, QRModal, ConfirmModal });
