// upload-modals.jsx — photo + letter upload sheets

const modalBackdropStyle = {
  position: 'absolute',
  top: 0, left: 0, right: 0, bottom: 0,
  zIndex: 300,
  background: 'rgba(20,16,10,0.5)',
  WebkitBackdropFilter: 'blur(4px)',
  backdropFilter: 'blur(4px)',
  display: 'flex',
  alignItems: 'flex-end',
  justifyContent: 'center',
  overflow: 'hidden',
  opacity: 1,
};

const modalSheetStyle = {
  width: '100%',
  background: 'var(--paper)',
  backgroundImage:
    'radial-gradient(ellipse at 12% 6%, rgba(232,90,62,0.08), transparent 55%),' +
    'radial-gradient(ellipse at 88% 92%, rgba(111,195,168,0.08), transparent 55%)',
  borderRadius: '22px 22px 0 0',
  padding: '18px 22px 28px',
  boxShadow: '0 -10px 40px rgba(0,0,0,0.3)',
  maxHeight: '86%',
  overflowY: 'auto',
  WebkitOverflowScrolling: 'touch',
  position: 'relative',
};

const PHOTO_UPLOAD_SCRIPT_URL = 'https://script.google.com/macros/s/AKfycbyE3rHm0Ysx-JCW1PXFZYSY9n08BUTfs54gbFTGWJck8JZT4_4h2NMP-vpDtVuO_LQx/exec';

const PhotoUploadModal = ({ onClose }) => {
  const [caption, setCaption] = React.useState('');
  const [date, setDate] = React.useState('');
  const [preview, setPreview] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [error, setError] = React.useState('');
  const inputRef = React.useRef(null);
  const fileNameRef = React.useRef('');

  const pickFile = () => inputRef.current?.click();

  const onFile = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setBusy(true);
    setError('');
    try {
      fileNameRef.current = file.name || `upload-${Date.now()}.jpg`;
      const dataUrl = await fileToCompressedDataURL(file);
      setPreview(dataUrl);
    } catch (err) { console.error(err); }
    setBusy(false);
  };

  const save = async () => {
    if (!preview) return;
    setBusy(true);
    setError('');
    try {
      await fetch(PHOTO_UPLOAD_SCRIPT_URL, {
        method: 'POST',
        mode: 'no-cors',
        headers: {
          'Content-Type': 'text/plain;charset=utf-8',
        },
        body: JSON.stringify({
          imageBase64: preview,
          fileName: fileNameRef.current || `upload-${Date.now()}.jpg`,
          caption: caption.trim(),
          date: date.trim(),
        }),
      });
      setSaved(true);
      window.dispatchEvent(new CustomEvent('es-drive-photos-refresh'));
      window.setTimeout(() => {
        window.dispatchEvent(new CustomEvent('es-drive-photos-refresh'));
        onClose();
      }, 1200);
    } catch (err) {
      console.error(err);
      setError('Upload failed. Please try again.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={modalBackdropStyle} onClick={onClose}>
      <div style={modalSheetStyle} onClick={e => e.stopPropagation()}>
        <div className="sheet-handle" />
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18, gap: 12 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="kicker">add a photo</div>
            <div className="display" style={{ fontSize: 24, fontWeight: 600, marginTop: 4, lineHeight: 1.15 }}>
              Drop a moment <em style={{ color: 'var(--coral)', fontStyle: 'italic', fontWeight: 500 }}>in the roll</em>
            </div>
          </div>
          <button className="btn-icon" onClick={onClose} aria-label="close" style={{ flexShrink: 0 }}>
            <svg width="16" height="16" viewBox="0 0 20 20"><path d="M5 5l10 10M15 5L5 15" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
          </button>
        </div>

        <input ref={inputRef} type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />

        {saved ? (
          <div style={{ padding: '56px 10px', textAlign: 'center' }}>
            <div style={{ fontSize: 56 }} className="pop-in">📸</div>
            <div className="display" style={{ fontSize: 24, marginTop: 14, fontStyle: 'italic', color: 'var(--coral)', fontWeight: 500 }}>
              Photo uploaded!
            </div>
            <div className="body-text" style={{ fontSize: 14, color: 'var(--ink-soft)', marginTop: 8 }}>
              It will appear in the shared Drive gallery shortly.
            </div>
          </div>
        ) : preview ? (
          <div style={{ position: 'relative', marginBottom: 16 }}>
            <div className="photo-tile" style={{ transform: 'rotate(-1deg)' }}>
              <div style={{ width: '100%', aspectRatio: '4 / 3', overflow: 'hidden', borderRadius: 2 }}>
                <img src={preview} alt="preview" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </div>
              {caption && (
                <div className="hand" style={{ fontSize: 18, marginTop: 10, paddingLeft: 4, color: 'var(--ink)' }}>
                  {caption}
                </div>
              )}
            </div>
            <button
              onClick={pickFile}
              style={{
                position: 'absolute', top: 4, right: 4,
                background: 'rgba(31,26,19,0.85)', color: 'var(--paper)',
                border: 'none', borderRadius: 999,
                padding: '5px 10px', fontSize: 10, fontWeight: 600,
                cursor: 'pointer',
              }}>
              Change
            </button>
          </div>
        ) : (
          <div className="upload-tile" style={{ aspectRatio: '4 / 3', minHeight: 180 }} onClick={pickFile}>
            {busy ? (
              <div className="mono" style={{ fontSize: 11 }}>Loading…</div>
            ) : (
              <>
                <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
                  <rect x="5" y="9" width="30" height="22" rx="3" stroke="currentColor" strokeWidth="2"/>
                  <circle cx="14" cy="17" r="2.5" fill="currentColor"/>
                  <path d="M9 28l9-9 7 7 4-4 6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Tap to pick a photo</div>
                <div className="mono" style={{ fontSize: 9, letterSpacing: '0.15em' }}>JPG · PNG · HEIC</div>
              </>
            )}
          </div>
        )}

        <div style={{ marginTop: 14 }}>
          <label className="field-label">Caption (optional)</label>
          <input className="input" placeholder="Leave blank if you want"
                 value={caption} onChange={e => setCaption(e.target.value)} maxLength={60}
                 disabled={busy || saved}/>
        </div>

        <div style={{ marginTop: 12 }}>
          <label className="field-label">Date / place (optional)</label>
          <input className="input" placeholder="Leave blank if you want"
                 value={date} onChange={e => setDate(e.target.value)} maxLength={30}
                 disabled={busy || saved}/>
        </div>

        {error && (
          <div style={{ fontSize: 12, color: 'var(--coral-deep)', marginTop: 10 }}>{error}</div>
        )}

        <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
          <button className="btn btn-ghost" onClick={onClose} style={{ flex: 1, justifyContent: 'center' }} disabled={busy}>
            Cancel
          </button>
          <button className="btn btn-coral" onClick={save} disabled={!preview || busy || saved}
                  style={{ flex: 2, justifyContent: 'center', opacity: (preview && !busy && !saved) ? 1 : 0.45 }}>
            {busy ? 'Uploading…' : saved ? 'Uploaded' : 'Upload to gallery'}
          </button>
        </div>
      </div>
    </div>
  );
};

const LetterWriteModal = ({ onClose, onAdd }) => {
  const [author, setAuthor] = React.useState('');
  const [role, setRole] = React.useState('');
  const [group, setGroup] = React.useState('');
  const [body, setBody] = React.useState('');
  const [saved, setSaved] = React.useState(false);

  const canSave = author.trim() && body.trim();

  const save = () => {
    if (!canSave) return;
    const today = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
    onAdd({
      author: author.trim(),
      role: role.trim() || 'Friend',
      group: group.trim() || 'From afar',
      date: today,
      sticker: 'heart',
      color: 'mint',
      body: body.trim().split(/\n\s*\n/).map(p => p.trim()).filter(Boolean),
      user: true,
    });
    setSaved(true);
    setTimeout(onClose, 720);
  };

  return (
    <div style={modalBackdropStyle} onClick={onClose}>
      <div style={modalSheetStyle} onClick={e => e.stopPropagation()}>
        <div className="sheet-handle" />
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18, gap: 12 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="kicker">write a letter</div>
            <div className="display" style={{ fontSize: 24, fontWeight: 600, marginTop: 4, lineHeight: 1.15 }}>
              A note for <em style={{ color: 'var(--coral)', fontStyle: 'italic', fontWeight: 500 }}>Ed & Sharon</em>
            </div>
          </div>
          <button className="btn-icon" onClick={onClose} aria-label="close" style={{ flexShrink: 0 }}>
            <svg width="16" height="16" viewBox="0 0 20 20"><path d="M5 5l10 10M15 5L5 15" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
          </button>
        </div>

        {saved ? (
          <div style={{ padding: '60px 10px', textAlign: 'center' }}>
            <div style={{ fontSize: 60 }} className="pop-in">💌</div>
            <div className="display" style={{ fontSize: 24, marginTop: 14, fontStyle: 'italic', color: 'var(--coral)', fontWeight: 500 }}>
              Letter sent!
            </div>
            <div className="body-text" style={{ fontSize: 14, color: 'var(--ink-soft)', marginTop: 8 }}>
              Added to the collection.
            </div>
          </div>
        ) : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <label className="field-label">Your name *</label>
                <input className="input" placeholder="e.g. Anna"
                       value={author} onChange={e => setAuthor(e.target.value)} maxLength={40}/>
              </div>
              <div>
                <label className="field-label">Role</label>
                <input className="input" placeholder="Sister, Friend…"
                       value={role} onChange={e => setRole(e.target.value)} maxLength={30}/>
              </div>
            </div>

            <div style={{ marginTop: 14 }}>
              <label className="field-label">Group / church (optional)</label>
              <input className="input" placeholder="e.g. Banqiao · Young Adults"
                     value={group} onChange={e => setGroup(e.target.value)} maxLength={40}/>
            </div>

            <div style={{ marginTop: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <label className="field-label">Your letter *</label>
                <span className="mono" style={{ fontSize: 9, color: 'var(--ink-dim)' }}>
                  {body.length}/4000
                </span>
              </div>
              <textarea className="textarea"
                        placeholder="Dear Ed & Sharon,&#10;&#10;Thank you for…&#10;&#10;— Your name"
                        value={body} onChange={e => setBody(e.target.value)} maxLength={4000}/>
              <div className="mono" style={{ fontSize: 9, color: 'var(--ink-dim)', marginTop: 4, fontStyle: 'italic' }}>
                Leave a blank line between paragraphs.
              </div>
            </div>

            <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
              <button className="btn btn-ghost" onClick={onClose} style={{ flex: 1, justifyContent: 'center' }}>
                Cancel
              </button>
              <button className="btn btn-coral" onClick={save} disabled={!canSave}
                      style={{ flex: 2, justifyContent: 'center', opacity: canSave ? 1 : 0.45 }}>
                ✉ Send letter
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { PhotoUploadModal, LetterWriteModal });
