// Screens 5 (Create) + 6 (Loading) + 10 (Email modal)

const PALETTE_OPTIONS = [
  { key: 'coastal',   label: 'Coastal', colors: ['#2d5d8a','#fbeee0','#e8d4c5'], grad: 'linear-gradient(135deg, #cfe0e8 0%, #e8d4c5 100%)' },
  { key: 'sunset',    label: 'Sunset',  colors: ['#7a4e8e','#e05a3d','#f3b94a'], grad: 'linear-gradient(135deg, #f3b94a 0%, #e05a3d 50%, #7a4e8e 100%)' },
  { key: 'garden',    label: 'Garden',  colors: ['#c6d4b8','#f0d4c0','#c88fa4'], grad: 'linear-gradient(135deg, #c6d4b8 0%, #f0d4c0 100%)' },
];

const EVENT_TYPES = ['Pool Party','Dinner','Bar Crawl','Brunch','Beach Day','Night in','Club Night','Spa Day','Other'];

function CreateTheme({ custom, setCustom, vibe, setVibe, dates, onBuild }) {
  const upd = (k, v) => setCustom({ ...custom, [k]: v });
  // Event type is single-select — pick one, picking another swaps it
  const event = custom.event || '';
  const setEvent = (e) => upd('event', event === e ? '' : e);
  const fileInputRef = React.useRef(null);

  const customColors = custom.customColors || ['#e05a3d', '#f3b94a', '#fbeee0'];
  const updColor = (i, col) => {
    const next = customColors.slice();
    next[i] = col;
    upd('customColors', next);
  };

  const build = () => {
    let palette;
    if (custom.palette === 'custom') {
      palette = { colors: customColors, grad: `linear-gradient(135deg, ${customColors[0]} 0%, ${customColors[1]} 50%, ${customColors[2]} 100%)` };
    } else if (custom.palette === 'ai') {
      // AI-decided default — pick sunset
      const p = PALETTE_OPTIONS.find(p => p.key === 'sunset');
      palette = { colors: p.colors, grad: p.grad };
    } else {
      const p = PALETTE_OPTIONS.find(p => p.key === custom.palette) || PALETTE_OPTIONS[0];
      palette = { colors: p.colors, grad: p.grad };
    }
    const newVibe = {
      key: 'custom-' + Date.now(),
      n: custom.name || 'Your custom theme',
      name: custom.name || 'Your custom theme',
      em: '✨',
      grad: palette.grad,
      palette: palette.colors,
    };
    setVibe && setVibe(newVibe);
    onBuild(newVibe);
  };

  // Downscale + base64-encode each image client-side so we stay under Vercel's request limit
  // and keep Claude's vision processing fast.
  const downscaleImage = (file, maxDim = 800, quality = 0.82) => new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      let { width, height } = img;
      const ratio = Math.min(maxDim / width, maxDim / height, 1);
      width = Math.round(width * ratio);
      height = Math.round(height * ratio);
      const canvas = document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);
      canvas.toBlob(blob => {
        if (!blob) return reject(new Error('canvas toBlob failed'));
        const reader = new FileReader();
        reader.onload = () => {
          const dataUrl = String(reader.result || '');
          const [meta, data] = dataUrl.split(',');
          const mt = (meta.match(/data:([^;]+)/) || [])[1] || 'image/jpeg';
          resolve({ mediaType: mt, data, name: file.name });
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      }, 'image/jpeg', quality);
    };
    img.onerror = reject;
    img.src = URL.createObjectURL(file);
  });

  const [pinUploading, setPinUploading] = React.useState(false);
  const onFilesPicked = async (e) => {
    const files = Array.from(e.target.files || []).slice(0, 5);
    if (!files.length) return;
    setPinUploading(true);
    try {
      const images = await Promise.all(files.map(f => downscaleImage(f)));
      upd('pinterestImages', images);
    } catch (err) {
      console.warn('Pin upload error:', err);
    }
    setPinUploading(false);
  };

  const pinImages = custom.pinterestImages || [];

  const showOtherInput = event === 'Other';

  return (
    <div style={{ background: TBL.cream, height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '24px 22px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Eyebrow>New theme</Eyebrow>
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: '0 22px 16px' }}>
        <div style={{ fontFamily: SERIF, fontSize: 34, lineHeight: 0.98, color: TBL.ink, letterSpacing: -1, marginBottom: 22 }}>
          <i>Build</i> a theme.
        </div>

        {/* Pinterest upload — now functional */}
        <div style={{ background: `linear-gradient(135deg, ${TBL.mint}30 0%, ${TBL.citrus}30 100%)`, border: `1.5px dashed ${TBL.jam}`, borderRadius: 18, padding: 20, marginBottom: 18, position: 'relative', overflow: 'hidden' }}>
          {Array.from({length: 6}).map((_,i) => (
            <div key={i} style={{ position: 'absolute', width: 4, height: 4, borderRadius: 999, background: TBL.jam, left: `${(i*47)%90}%`, top: `${(i*31)%90}%`, opacity: 0.5 }}/>
          ))}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, position: 'relative' }}>
            <div style={{ fontFamily: MONO, fontSize: 9, letterSpacing: 2, background: TBL.jam, color: TBL.cream, padding: '3px 7px', borderRadius: 4 }}>BETA</div>
            <Eyebrow>Fastest way</Eyebrow>
          </div>
          <div style={{ fontFamily: SERIF, fontSize: 20, fontStyle: 'italic', color: TBL.ink, letterSpacing: -0.4, marginBottom: 4, position: 'relative' }}>Upload your Pinterest board</div>
          <div style={{ fontSize: 12, color: TBL.subtle, marginBottom: 14, position: 'relative' }}>Drop screenshots — we'll read the palette and build the list from it.</div>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            multiple
            onChange={onFilesPicked}
            style={{ display: 'none' }}
          />
          <SecondaryBtn size="sm" full onClick={() => fileInputRef.current && fileInputRef.current.click()}>
            {pinUploading
              ? '📌 Reading images…'
              : (pinImages.length > 0 ? `📌 ${pinImages.length} screenshot${pinImages.length === 1 ? '' : 's'} ready · tap to change` : '📌 Choose screenshots')}
          </SecondaryBtn>
          {pinImages.length > 0 && (
            <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap', position: 'relative' }}>
              {pinImages.map((img, i) => (
                <div key={i} style={{ position: 'relative' }}>
                  <img
                    src={`data:${img.mediaType};base64,${img.data}`}
                    alt={img.name}
                    style={{ width: 56, height: 56, objectFit: 'cover', borderRadius: 8, border: `1px solid ${TBL.line}` }}
                  />
                  <button
                    onClick={() => upd('pinterestImages', pinImages.filter((_, j) => j !== i))}
                    aria-label="Remove image"
                    style={{
                      position: 'absolute', top: -6, right: -6, width: 18, height: 18,
                      borderRadius: 999, background: TBL.ink, color: TBL.cream, border: 'none',
                      cursor: 'pointer', fontSize: 11, lineHeight: 1,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>×</button>
                </div>
              ))}
            </div>
          )}
          <div style={{ fontFamily: MONO, fontSize: 9, color: TBL.mute, marginTop: pinImages.length > 0 ? 8 : 6, letterSpacing: 0.6, position: 'relative' }}>
            {pinImages.length > 0
              ? 'AI WILL READ THESE FOR PALETTE, MOOD, AND ITEMS · UP TO 5 IMAGES'
              : 'UP TO 5 SCREENSHOTS · AI READS PALETTE + MOOD + ITEMS'}
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '10px 0 18px' }}>
          <div style={{ flex: 1, height: 1, background: TBL.line }}/>
          <div style={{ fontFamily: MONO, fontSize: 10, color: TBL.mute, letterSpacing: 2 }}>OR DESCRIBE IT</div>
          <div style={{ flex: 1, height: 1, background: TBL.line }}/>
        </div>

        {/* Theme name (single field — also doubles as event name) */}
        <InputField label="Name this theme" value={custom.name} onChange={(v) => upd('name', v)} placeholder="e.g. Saturday pool party"/>
        <div style={{ height: 14 }}/>

        <SubLabel>Describe the vibe</SubLabel>
        <textarea
          value={custom.description || ''}
          onChange={(e) => upd('description', e.target.value)}
          placeholder="Navy and white everything, pearls, champagne, rattan. Nantucket meets a yacht club."
          className="tbl-input"
          style={{
            width: '100%', background: '#fff', border: `1px solid ${TBL.line}`, borderRadius: 14,
            padding: 14, marginBottom: 18, fontFamily: SANS, fontSize: 14,
            color: TBL.ink, lineHeight: 1.5, minHeight: 90, resize: 'vertical', outline: 'none',
          }}
          onFocus={(e) => e.target.style.borderColor = TBL.jam}
          onBlur={(e) => e.target.style.borderColor = TBL.line}
        />

        <SubLabel>Event type · pick one</SubLabel>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: showOtherInput ? 10 : 18 }}>
          {EVENT_TYPES.map(e => <Chip key={e} active={event === e} onClick={() => setEvent(e)}>{e}</Chip>)}
        </div>
        {showOtherInput && (
          <div style={{ marginBottom: 18 }}>
            <input
              type="text"
              value={custom.otherEvent || ''}
              onChange={(e) => upd('otherEvent', e.target.value)}
              placeholder="e.g. Private yacht tour"
              className="tbl-input"
              style={{
                width: '100%', background: '#fff', border: `1px solid ${TBL.line}`, borderRadius: 12,
                padding: '11px 14px', fontFamily: SANS, fontSize: 14, color: TBL.ink, outline: 'none',
              }}
              onFocus={(e) => e.target.style.borderColor = TBL.jam}
              onBlur={(e) => e.target.style.borderColor = TBL.line}
            />
          </div>
        )}

        <SubLabel>Palette</SubLabel>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 10 }}>
          {PALETTE_OPTIONS.map(p => (
            <button key={p.key} onClick={() => upd('palette', p.key)} style={{
              background: '#fff',
              border: custom.palette === p.key ? `1.5px solid ${TBL.jam}` : `1px solid ${TBL.line}`,
              borderRadius: 12, padding: '10px 6px', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
            }}>
              <div style={{ display: 'flex', gap: 3 }}>
                {p.colors.map(c => <div key={c} style={{ width: 14, height: 14, borderRadius: 999, background: c, border: '1px solid rgba(0,0,0,0.1)' }}/>)}
              </div>
              <div style={{ fontFamily: SANS, fontSize: 10, color: TBL.mute }}>{p.label}</div>
            </button>
          ))}
          <button onClick={() => upd('palette', 'ai')} style={{
            background: '#fff',
            border: custom.palette === 'ai' ? `1.5px solid ${TBL.jam}` : `1px solid ${TBL.line}`,
            borderRadius: 12, padding: '10px 6px', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
          }}>
            <div style={{ fontSize: 18, lineHeight: 1 }}>✨</div>
            <div style={{ fontFamily: SANS, fontSize: 10, color: TBL.mute }}>Let AI pick</div>
          </button>
        </div>
        <button onClick={() => upd('palette', 'custom')} style={{
          width: '100%',
          background: '#fff',
          border: custom.palette === 'custom' ? `1.5px solid ${TBL.jam}` : `1px solid ${TBL.line}`,
          borderRadius: 12, padding: '12px 14px', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
          marginBottom: custom.palette === 'custom' ? 10 : 18,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ display: 'flex', gap: 3 }}>
              {customColors.map((c, i) => <div key={i} style={{ width: 16, height: 16, borderRadius: 999, background: c, border: '1px solid rgba(0,0,0,0.1)' }}/>)}
            </div>
            <span style={{ fontFamily: SANS, fontSize: 13, color: TBL.ink }}>Pick my own colours</span>
          </div>
          <svg width="6" height="10" viewBox="0 0 7 12"><path d="M1 1 L6 6 L1 11" stroke={TBL.mute} strokeWidth="1.5" fill="none" strokeLinecap="round"/></svg>
        </button>
        {custom.palette === 'custom' && (
          <div style={{ background: '#fff', border: `1px solid ${TBL.line}`, borderRadius: 14, padding: 14, marginBottom: 18 }}>
            <SubLabel>Pick three colours</SubLabel>
            <div style={{ display: 'flex', gap: 10, marginBottom: 10 }}>
              {customColors.map((c, i) => (
                <label key={i} style={{ flex: 1, position: 'relative', cursor: 'pointer' }}>
                  <input
                    type="color"
                    value={c}
                    onChange={(e) => updColor(i, e.target.value)}
                    style={{ position: 'absolute', inset: 0, opacity: 0, cursor: 'pointer' }}
                  />
                  <div style={{
                    background: c, height: 52, borderRadius: 10,
                    border: '2px solid rgba(0,0,0,0.08)',
                    display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
                    padding: 6, fontFamily: MONO, fontSize: 10, color: '#fff',
                    textShadow: '0 1px 2px rgba(0,0,0,0.4)',
                  }}>{c.toUpperCase()}</div>
                </label>
              ))}
            </div>
            <div style={{ fontSize: 11, color: TBL.subtle, lineHeight: 1.4 }}>
              We'll match items as closely as possible to these colours across our retailers.
            </div>
          </div>
        )}

        <div style={{ marginBottom: 18 }}>
          <SubLabel>Guests for this theme</SubLabel>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <Stepper val={custom.guests || (dates ? dates.guests : 8)} min={2} max={30} onChange={(v) => upd('guests', v)}/>
            <div style={{ fontSize: 12, color: TBL.subtle }}>Can differ per theme (e.g. 6 at spa, 12 at the bar)</div>
          </div>
        </div>

        <div style={{ background: `${TBL.mint}12`, border: `1px solid ${TBL.mint}40`, borderRadius: 14, padding: 14, marginTop: 4 }}>
          <Eyebrow color={TBL.ink} style={{ marginBottom: 6 }}>From your favourite retailers</Eyebrow>
          <div style={{ fontSize: 12, color: TBL.subtle, lineHeight: 1.5 }}>
            Every theme pulls a balanced mix from <b style={{ color: TBL.ink }}>Shein, Amazon, Etsy, and Temu</b> — so you can compare prices across brands and pick whichever works for your group.
          </div>
        </div>
      </div>
      <div style={{ padding: '14px 22px 18px', background: TBL.cream, borderTop: `1px solid ${TBL.line}` }}>
        <PrimaryBtn full size="lg" onClick={build}>Build my theme board ✨</PrimaryBtn>
      </div>
    </div>
  );
}

// ── Loading ──
function LoadingScreen({ vibe }) {
  const msgs = [
    'Pulling inspiration from 2,400 themed parties…',
    'Curating the perfect palette…',
    'Mixing champagne with chic…',
    'Matching sashes to the palette…',
    'Finalizing the favor list…',
    'Almost there — last touches…',
  ];
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setIdx(i => (i + 1) % msgs.length), 600); return () => clearInterval(t); }, []);
  const [rot, setRot] = React.useState(0);
  React.useEffect(() => { let raf; const tick = () => { setRot(r => (r + 1.5) % 360); raf = requestAnimationFrame(tick); }; raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf); }, []);
  const vibeName = vibe && (vibe.n || vibe.name) ? (vibe.n || vibe.name).toUpperCase() : 'YOUR THEME';
  return (
    <div style={{ background: TBL.cream, height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 32, textAlign: 'center' }}>
      <div style={{ background: TBL.jam, color: TBL.cream, padding: '6px 14px', borderRadius: 999, fontFamily: MONO, fontSize: 10, letterSpacing: 2, marginBottom: 40 }}>
        BUILDING · {vibeName}
      </div>
      <svg width="80" height="80" viewBox="0 0 80 80" style={{ transform: `rotate(${rot}deg)`, marginBottom: 28 }}>
        <circle cx="40" cy="40" r="32" fill="none" stroke={TBL.line} strokeWidth="3"/>
        <circle cx="40" cy="40" r="32" fill="none" stroke={TBL.jam} strokeWidth="3" strokeLinecap="round" strokeDasharray="60 300"/>
        <path d="M40 18 L43 34 L58 37 L45 45 L48 60 L40 52 L32 60 L35 45 L22 37 L37 34 Z" fill={TBL.citrus} transform="scale(0.5) translate(40, 40)"/>
      </svg>
      <div style={{ fontFamily: SERIF, fontSize: 32, fontStyle: 'italic', color: TBL.ink, letterSpacing: -0.8, lineHeight: 1.05, marginBottom: 18 }}>
        Curating the<br/>perfect chaos…
      </div>
      <div style={{ fontFamily: SANS, fontSize: 13, color: TBL.subtle, minHeight: 40, transition: 'opacity 0.3s' }}>
        {msgs[idx]}
      </div>
    </div>
  );
}

// ── Email capture modal ──
function EmailModal({ user, onClose }) {
  const [email, setEmail] = React.useState('');
  const [saved, setSaved] = React.useState(false);
  const save = (e) => { e.preventDefault(); if (email.includes('@')) setSaved(true); };
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(42,26,31,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, zIndex: 200 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TBL.cream, borderRadius: 24, padding: 28, width: '100%', textAlign: 'center' }}>
        {!saved ? (
          <>
            <div style={{ fontSize: 40, marginBottom: 12 }}>💌</div>
            <div style={{ fontFamily: SERIF, fontSize: 26, color: TBL.ink, fontStyle: 'italic', letterSpacing: -0.5, lineHeight: 1.1, marginBottom: 10 }}>
              Email me a<br/>copy of this list.
            </div>
            <div style={{ fontSize: 13, color: TBL.subtle, lineHeight: 1.5, marginBottom: 20 }}>
              Your list is already saved in this browser — drop your email and we'll send you a link so you can come back from any device when accounts launch this spring.
            </div>
            <form onSubmit={save}>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={user && user.name ? `${user.name.toLowerCase()}@email.com` : 'your@email.com'}
                className="tbl-input"
                style={{
                  width: '100%', background: '#fff', border: `1px solid ${TBL.line}`, borderRadius: 12,
                  padding: '13px 14px', fontFamily: SANS, fontSize: 14, color: TBL.ink,
                  marginBottom: 14, outline: 'none', textAlign: 'left',
                }}
                onFocus={(e) => e.target.style.borderColor = TBL.jam}
                onBlur={(e) => e.target.style.borderColor = TBL.line}
                autoFocus
              />
              <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
                <SecondaryBtn full size="md" onClick={onClose}>Not now</SecondaryBtn>
                <button type="submit" style={{
                  flex: 1, background: TBL.jam, color: TBL.cream, border: 'none',
                  padding: '13px 22px', borderRadius: 999, fontFamily: SANS, fontSize: 14, fontWeight: 500, cursor: 'pointer',
                  boxShadow: '0 1px 2px rgba(224,90,61,0.25), 0 4px 12px rgba(224,90,61,0.2)',
                }}>Save theme</button>
              </div>
              <div style={{ fontSize: 10, color: TBL.mute, lineHeight: 1.4 }}>
                By continuing you agree to our Terms and Privacy Policy.
              </div>
            </form>
          </>
        ) : (
          <>
            <div style={{ fontSize: 40, marginBottom: 12 }}>🥂</div>
            <div style={{ fontFamily: SERIF, fontSize: 26, color: TBL.ink, fontStyle: 'italic', letterSpacing: -0.5, lineHeight: 1.1, marginBottom: 10 }}>
              Saved.
            </div>
            <div style={{ fontSize: 13, color: TBL.subtle, lineHeight: 1.5, marginBottom: 20 }}>
              We'll email you a link to your list within the minute. You can come back to edit anytime.
            </div>
            <PrimaryBtn full size="md" onClick={onClose}>Back to theme →</PrimaryBtn>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CreateTheme, LoadingScreen, EmailModal, PALETTE_OPTIONS });
