// Thank-you composer modal + email template builder.
//
// The list owner opens this from the "Gifts taken" section. They can:
//   - upload a single photo to include in every email
//   - tweak the shared message template (placeholders: {NAME}, {GIFT}, {YOU})
//   - select which recipients to send to (defaults: everyone with an email
//     and who hasn't already been thanked)
//   - send — one POST per recipient, with the placeholders substituted

const { useEffect: _te, useState: _ts, useRef: _tr, useMemo: _tm } = React;

// Build an email-safe HTML string. Uses table layout + inline styles so it
// renders in Outlook + Gmail + Apple Mail without surprises.
function buildThankYouEmail({ recipientName, giftName, message, senderName, photoUrl, signOffName }) {
  // Sanitize a few HTML special chars in user-controlled fields.
  const esc = (s) => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  const messageHtml = esc(message).replace(/\n\n+/g, '</p><p style="margin:0 0 14px;">').replace(/\n/g, '<br>');

  const photoBlock = photoUrl ? `
    <tr>
      <td style="padding: 0 28px 24px;">
        <img src="${esc(photoUrl)}" alt="" width="100%" style="display:block;border-radius:14px;border:0;outline:none;max-width:100%;height:auto;" />
      </td>
    </tr>` : '';

  return `<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Thank you</title>
</head>
<body style="margin:0; padding:0; background:#efe7d4; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; color:#1f1d18;">
  <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background:#efe7d4; padding: 32px 16px;">
    <tr>
      <td align="center">
        <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="540" style="max-width:540px; background:#fbf9f2; border-radius:18px; overflow:hidden; box-shadow: 0 6px 28px rgba(31,29,24,0.08);">
          <tr>
            <td align="center" style="padding: 36px 32px 24px;">
              <!-- Brand mark — gold star with a coral mini-star + sage dot -->
              <table role="presentation" cellpadding="0" cellspacing="0" border="0">
                <tr><td style="font-size:34px; line-height:1;">
                  <span style="color:#e0a94c;">★</span>
                </td></tr>
              </table>
            </td>
          </tr>
          ${photoBlock}
          <tr>
            <td align="center" style="padding: 0 28px 16px;">
              <p style="margin:0 0 6px; font-size: 11px; letter-spacing: 0.22em; text-transform: uppercase; color:#8a6326; font-weight:600;">
                A note from ${esc(senderName) || 'the new parents'}
              </p>
              <h1 style="margin:0 0 20px; font-family: 'Fredoka', 'Trebuchet MS', sans-serif; font-weight:700; font-size:34px; line-height:1.08; letter-spacing:-0.02em; color:#1f1d18;">
                Thank you, <span style="color:#cf5d4a;">${esc(recipientName) || 'friend'}</span>
              </h1>
            </td>
          </tr>
          <tr>
            <td style="padding: 0 32px 32px;">
              <p style="margin: 0 0 14px; font-size: 16px; line-height: 1.6; color: #3c3a33;">${messageHtml || ''}</p>
            </td>
          </tr>
          <tr>
            <td align="center" style="padding: 0 32px 28px;">
              <p style="margin: 0; font-family: 'Fredoka', 'Trebuchet MS', sans-serif; font-weight: 600; font-size: 15px; color:#1f1d18;">
                Love,<br>${esc(signOffName) || esc(senderName) || ''}
              </p>
            </td>
          </tr>
          <tr>
            <td style="border-top: 1px solid #e9e2cf; padding: 20px 32px; text-align:center;">
              <p style="margin:0; font-size: 11px; letter-spacing: 0.16em; text-transform: uppercase; color:#736f63;">
                <span style="color:#e0a94c;">★</span>
                &nbsp;Sent with MagicRascals
              </p>
            </td>
          </tr>
        </table>
        <p style="font-size: 11px; color: #8a8674; margin-top: 16px; max-width: 540px; padding: 0 16px;">
          You received this because you claimed a gift on a public registry on MagicRascals.
          Reply directly to this email to message ${esc(senderName) || 'the parents'} back.
        </p>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

const DEFAULT_TEMPLATE = `Thank you so much for the {GIFT}! It really means the world that you thought of us. We can't wait to put it to use.

With so much love,
{YOU}`;

function substitute(template, vars) {
  return String(template || '')
    .replace(/\{NAME\}/g, vars.NAME || 'friend')
    .replace(/\{GIFT\}/g, vars.GIFT || 'gift')
    .replace(/\{YOU\}/g, vars.YOU || '');
}

function ThankYouComposer({ open, list, claims, items, productMap, onClose, onSent, defaultSenderName }) {
  const [photoUrl, setPhotoUrl] = _ts('');
  const [photoBusy, setPhotoBusy] = _ts(false);
  const [template, setTemplate] = _ts(DEFAULT_TEMPLATE);
  const [senderName, setSenderName] = _ts(defaultSenderName || '');
  const [subject, setSubject] = _ts('Thank you for the gift!');
  const [selected, setSelected] = _ts(() => new Set());
  const [sendingIdx, setSendingIdx] = _ts(-1);
  const [sentCount, setSentCount] = _ts(0);
  const [errMsg, setErrMsg] = _ts('');
  const [doneMsg, setDoneMsg] = _ts('');
  const [previewIdx, setPreviewIdx] = _ts(0);
  const [perRecipientMode, setPerRecipientMode] = _ts(false);
  const [perRecipientMessages, setPerRecipientMessages] = _ts({});
  const fileRef = _tr(null);

  // Eligible claims: have an email and haven't already been thanked
  const eligibleClaims = _tm(() => {
    return (claims || []).filter(c => c.buyer_email && !c.thanked_at);
  }, [claims]);

  // Reset state when modal re-opens
  _te(() => {
    if (open) {
      const initial = new Set(eligibleClaims.map(c => c.id));
      setSelected(initial);
      setSentCount(0);
      setErrMsg('');
      setDoneMsg('');
      setPreviewIdx(0);
      setPerRecipientMode(false);
      setPerRecipientMessages({});
      setSenderName(defaultSenderName || '');
    }
  }, [open]);

  if (!open || !list) return null;

  const claimById = {};
  (claims || []).forEach(c => { claimById[c.id] = c; });
  const itemById = {};
  (items || []).forEach(it => { itemById[it.id] = it; });

  const resolveGiftName = (claim) => {
    const item = claim.item_id ? itemById[claim.item_id] : null;
    if (item && item.custom_name) return item.custom_name;
    const p = claim.product_id ? productMap[claim.product_id] : null;
    if (p) return p.name;
    return 'gift';
  };

  const handlePhoto = async (file) => {
    if (!file) return;
    setPhotoBusy(true);
    try {
      const res = await uploadOrEncodeImage(file);
      if (res.hosted) {
        setPhotoUrl(res.url);
      } else {
        // Base64 data URLs in emails are huge and often get filtered as spam.
        // Warn the user but allow it.
        setPhotoUrl(res.url);
        setErrMsg('Photo couldn\'t be uploaded to Storage — it\'ll be embedded inline (works but the email file size is larger). Sign in to host photos properly.');
      }
    } catch (e) {
      setErrMsg('Couldn\'t read the photo: ' + e.message);
    } finally {
      setPhotoBusy(false);
    }
  };

  const selectedClaims = eligibleClaims.filter(c => selected.has(c.id));

  // Build the preview for one claim
  const previewClaim = selectedClaims[previewIdx] || eligibleClaims[0];
  const previewVars = previewClaim ? {
    NAME: previewClaim.buyer_name,
    GIFT: resolveGiftName(previewClaim),
    YOU:  senderName || 'Us',
  } : { NAME: 'Friend', GIFT: 'gift', YOU: senderName };
  const effectiveTemplate = perRecipientMode && previewClaim
    ? (perRecipientMessages[previewClaim.id] ?? template)
    : template;
  const previewHtml = buildThankYouEmail({
    recipientName: previewVars.NAME,
    giftName:      previewVars.GIFT,
    message:       substitute(effectiveTemplate, previewVars),
    senderName:    senderName,
    signOffName:   senderName,
    photoUrl,
  });

  const send = async () => {
    if (selectedClaims.length === 0) return;
    setErrMsg('');
    setDoneMsg('');
    setSentCount(0);

    for (let i = 0; i < selectedClaims.length; i++) {
      const claim = selectedClaims[i];
      setSendingIdx(i);
      const vars = {
        NAME: claim.buyer_name,
        GIFT: resolveGiftName(claim),
        YOU:  senderName || 'Us',
      };
      const messageTpl = perRecipientMode
        ? (perRecipientMessages[claim.id] ?? template)
        : template;
      const html = buildThankYouEmail({
        recipientName: vars.NAME,
        giftName:      vars.GIFT,
        message:       substitute(messageTpl, vars),
        senderName,
        signOffName:   senderName,
        photoUrl,
      });
      try {
        const resp = await fetch('/api/send-thank-you', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            to:      claim.buyer_email,
            subject: subject || 'Thank you for the gift!',
            html,
          }),
        });
        const json = await resp.json();
        if (!resp.ok || !json.ok) {
          setErrMsg(`Failed for ${claim.buyer_email}: ${json.error || resp.statusText}`);
          // Keep going — we'd rather get most of them than stop on one
        } else {
          // Mark thanked + log to thank_you_sent
          if (window.MR && window.MR.lists) {
            await window.MR.lists.markClaimThanked(claim.id, true);
            try {
              await window.MR.supabase.from('thank_you_sent').insert({
                claim_id:        claim.id,
                list_id:         list.id,
                sent_by:         (window.MR.user._session && window.MR.user._session.user.id) || null,
                recipient_email: claim.buyer_email,
                recipient_name:  claim.buyer_name,
                subject,
                message_html:    html.slice(0, 5000),
                photo_url:       photoUrl || null,
                resend_id:       json.id || null,
              });
            } catch (e) { /* audit log failure is non-fatal */ }
          }
          setSentCount(prev => prev + 1);
        }
      } catch (e) {
        setErrMsg(`Network error on ${claim.buyer_email}: ${e.message}`);
      }
    }
    setSendingIdx(-1);
    setDoneMsg(`Sent ${selectedClaims.length === 1 ? '1 thank-you' : `${selectedClaims.length} thank-yous`}.`);
    if (onSent) onSent();
  };

  const toggleSelected = (id, on) => {
    setSelected(prev => {
      const next = new Set(prev);
      if (on) next.add(id); else next.delete(id);
      return next;
    });
  };
  const toggleAll = () => {
    if (selected.size === eligibleClaims.length) setSelected(new Set());
    else setSelected(new Set(eligibleClaims.map(c => c.id)));
  };

  return (
    <>
      <div className="auth-scrim" onClick={onClose} />
      <div className="thankyou-modal" role="dialog" aria-modal="true" aria-label="Send thank-you notes">
        <div className="thankyou-modal-head">
          <div>
            <div className="thankyou-eyebrow">Gratitude time</div>
            <h2 className="thankyou-h">Send thank-yous</h2>
          </div>
          <button type="button" className="thankyou-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6 L18 18 M18 6 L6 18"/></svg>
          </button>
        </div>

        {eligibleClaims.length === 0 ? (
          <div className="thankyou-empty">
            <p>There's nobody to thank yet — claims need to include an email address, and you can only send to people you haven't thanked already.</p>
          </div>
        ) : (
        <div className="thankyou-body">
          {/* LEFT — composer fields */}
          <div className="thankyou-left">

            {/* Photo */}
            <div className="thankyou-field">
              <span className="thankyou-lbl">Photo (optional)</span>
              {photoUrl ? (
                <div className="thankyou-photo-preview">
                  <img src={photoUrl} alt="" />
                  <button type="button" className="thankyou-photo-remove" onClick={() => setPhotoUrl('')}>Remove</button>
                </div>
              ) : (
                <button type="button" className="thankyou-photo-add" onClick={() => fileRef.current && fileRef.current.click()} disabled={photoBusy}>
                  {photoBusy ? 'Uploading…' : 'Add a photo'}
                  <span className="thankyou-photo-hint">Show off baby, or the gift in action ✨</span>
                </button>
              )}
              <input ref={fileRef} type="file" accept="image/*" capture="environment" style={{ display: 'none' }}
                onChange={(e) => { const f = e.target.files && e.target.files[0]; if (f) handlePhoto(f); e.target.value = ''; }}
              />
            </div>

            {/* Sender name */}
            <div className="thankyou-field">
              <span className="thankyou-lbl">Sign off as</span>
              <input
                type="text"
                className="thankyou-input"
                placeholder="Sarah & Mike"
                value={senderName}
                onChange={(e) => setSenderName(e.target.value)}
              />
            </div>

            {/* Subject */}
            <div className="thankyou-field">
              <span className="thankyou-lbl">Subject line</span>
              <input
                type="text"
                className="thankyou-input"
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
              />
            </div>

            {/* Message */}
            <div className="thankyou-field">
              <span className="thankyou-lbl">
                Message
                <label className="thankyou-percheck">
                  <input type="checkbox" checked={perRecipientMode} onChange={(e) => setPerRecipientMode(e.target.checked)} />
                  Personalise per person
                </label>
              </span>
              <textarea
                className="thankyou-textarea"
                rows={7}
                placeholder="Write something warm…"
                value={perRecipientMode && previewClaim
                  ? (perRecipientMessages[previewClaim.id] ?? template)
                  : template
                }
                onChange={(e) => {
                  if (perRecipientMode && previewClaim) {
                    setPerRecipientMessages(prev => ({ ...prev, [previewClaim.id]: e.target.value }));
                  } else {
                    setTemplate(e.target.value);
                  }
                }}
              />
              <div className="thankyou-help">
                Placeholders: <code>{'{NAME}'}</code> (their name), <code>{'{GIFT}'}</code> (what they got), <code>{'{YOU}'}</code> (sign-off name).
              </div>
            </div>

            {/* Recipients */}
            <div className="thankyou-field">
              <span className="thankyou-lbl">
                Recipients
                <button type="button" className="thankyou-selectall" onClick={toggleAll}>
                  {selected.size === eligibleClaims.length ? 'Deselect all' : 'Select all'}
                </button>
              </span>
              <ul className="thankyou-recipients">
                {eligibleClaims.map((c, i) => (
                  <li key={c.id} className={`thankyou-recipient${selected.has(c.id) ? ' is-on' : ''}${perRecipientMode && previewClaim && c.id === previewClaim.id ? ' is-previewing' : ''}`}>
                    <label>
                      <input type="checkbox" checked={selected.has(c.id)} onChange={(e) => toggleSelected(c.id, e.target.checked)} />
                      <span className="thankyou-recipient-name">{c.buyer_name}</span>
                      <span className="thankyou-recipient-email">{c.buyer_email}</span>
                      <span className="thankyou-recipient-gift">· {resolveGiftName(c)}</span>
                    </label>
                    {perRecipientMode && (
                      <button type="button" className="thankyou-preview-pick" onClick={() => setPreviewIdx(selectedClaims.findIndex(s => s.id === c.id))} title="Preview &amp; edit this person's email">Edit</button>
                    )}
                  </li>
                ))}
              </ul>
            </div>

            {errMsg && <div className="auth-err">{errMsg}</div>}
            {doneMsg && <div className="thankyou-done">✓ {doneMsg}</div>}

            <div className="thankyou-actions">
              <button type="button" className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 16px' }}>
                <span>{doneMsg ? 'Close' : 'Cancel'}</span>
              </button>
              <button
                type="button"
                className="btn"
                onClick={send}
                disabled={selectedClaims.length === 0 || sendingIdx >= 0}
                style={{ width: 'auto', padding: '10px 18px' }}
              >
                <span className="btn-row">
                  {sendingIdx >= 0
                    ? `Sending ${sendingIdx + 1} / ${selectedClaims.length}…`
                    : doneMsg
                      ? '✓ Done'
                      : `Send ${selectedClaims.length || ''}`.trim()}
                </span>
                <span className="arrow">→</span>
              </button>
            </div>
          </div>

          {/* RIGHT — preview pane */}
          <div className="thankyou-right">
            <div className="thankyou-preview-head">
              <div className="thankyou-preview-eyebrow">Preview</div>
              <div className="thankyou-preview-meta">
                {previewClaim && <>To: <strong>{previewClaim.buyer_name}</strong> · {previewClaim.buyer_email}</>}
              </div>
              {selectedClaims.length > 1 && (
                <div className="thankyou-preview-pager">
                  <button type="button" onClick={() => setPreviewIdx(i => Math.max(0, i - 1))} disabled={previewIdx === 0}>‹</button>
                  <span>{previewIdx + 1} / {selectedClaims.length}</span>
                  <button type="button" onClick={() => setPreviewIdx(i => Math.min(selectedClaims.length - 1, i + 1))} disabled={previewIdx >= selectedClaims.length - 1}>›</button>
                </div>
              )}
            </div>
            <iframe
              className="thankyou-preview-frame"
              title="Email preview"
              srcDoc={previewHtml}
              sandbox=""
            />
          </div>
        </div>
        )}
      </div>
    </>
  );
}

window.ThankYouComposer = ThankYouComposer;
