/* ============================================
   SHARE MODAL & CREATE PLAYLIST MODAL
   ============================================ */

function ShareModal({ open, onClose, title = 'Share', subtitle, url = 'aimusic.studio/p/heat-check' }) {
  const toast = useToast();
  if (!open) return null;
  const targets = [
    { key: 'wa', label: 'WhatsApp', cls: 'wa', svg: <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.6-.8-1.9-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.8 1-.2.2-.3.2-.6.1-.3-.2-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.4-.8-1.9-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.2.3-.9.9-.9 2.2 0 1.3.9 2.5 1.1 2.7.1.2 1.9 2.9 4.5 4 .6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.6-.6 1.8-1.3.2-.6.2-1.2.2-1.3-.1-.1-.2-.2-.5-.3z"/><path d="M12 2C6.5 2 2 6.5 2 12c0 1.9.5 3.7 1.5 5.3L2 22l4.8-1.5C8.4 21.5 10.1 22 12 22c5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18c-1.7 0-3.3-.5-4.7-1.3l-.3-.2-3.4 1 .9-3.3-.2-.3C3.5 14.5 3 13.3 3 12c0-5 4-9 9-9s9 4 9 9-4 9-9 9z"/></svg> },
    { key: 'ig', label: 'Instagram', cls: 'ig', svg: <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg> },
    { key: 'fb', label: 'Facebook', cls: 'fb', svg: <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M14 9h3V6h-3c-1.7 0-3 1.3-3 3v2H8v3h3v8h3v-8h3l1-3h-4V9z"/></svg> },
    { key: 'tg', label: 'Telegram', cls: 'tg', svg: <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M21 4L2 11l6 2 2 6 3-3 4 3 4-15z M9.5 14.5L17 7l-6 8z"/></svg> },
    { key: 'tw', label: 'X / Twitter', cls: 'tw', svg: <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M17.5 3h3l-7 8 8 10h-6.4l-5-6.3L4.5 21h-3l7.4-8.4L1 3h6.6l4.6 5.9z"/></svg> },
    { key: 'em', label: 'Email', cls: 'em', svg: <Icon name="mail" size={20} /> },
    { key: 'cp', label: 'Copy link', cls: 'cp', svg: <Icon name="link" size={20} /> },
    { key: 'qr', label: 'QR code', cls: 'qr', svg: <Icon name="qr" size={20} /> },
  ];
  const [showQR, setShowQR] = React.useState(false);
  const fullUrl = url.startsWith('http') ? url : 'https://' + url;

  // Per-platform desktop web URLs (fallback when Web Share API isn't available)
  const webShareUrls = {
    wa: `https://wa.me/?text=${encodeURIComponent(title + '\n' + fullUrl)}`,
    ig: null, // Instagram has no web share URL; copy + instruct
    fb: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(fullUrl)}`,
    tg: `https://t.me/share/url?url=${encodeURIComponent(fullUrl)}&text=${encodeURIComponent(title)}`,
    tw: `https://twitter.com/intent/tweet?url=${encodeURIComponent(fullUrl)}&text=${encodeURIComponent(title)}`,
    em: `mailto:?subject=${encodeURIComponent(title)}&body=${encodeURIComponent(fullUrl)}`,
  };

  const handleShare = async (key) => {
    if (key === 'cp') {
      try { await navigator.clipboard.writeText(fullUrl); } catch { /* ignore */ }
      toast('Link copied to clipboard', 'success');
      return;
    }
    if (key === 'qr') { setShowQR(true); return; }

    // On mobile: Web Share API opens the native share sheet (WhatsApp, Instagram, etc.)
    if (navigator.share) {
      try {
        await navigator.share({ title, url: fullUrl });
        onClose();
      } catch (e) {
        // AbortError = user cancelled — don't show error
        if (e?.name !== 'AbortError') {
          await navigator.clipboard?.writeText(fullUrl);
          toast('Link copied to clipboard', 'success');
        }
      }
      return;
    }

    // Desktop fallback: open the platform's web share URL in a new tab
    const shareUrl = webShareUrls[key];
    if (shareUrl) {
      window.open(shareUrl, '_blank', 'noopener,noreferrer');
    } else {
      // Instagram (and any other platform with no web URL): copy link
      try { await navigator.clipboard.writeText(fullUrl); } catch { /* ignore */ }
      toast('Link copied — paste into Instagram', 'success');
    }
    setTimeout(onClose, 600);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal glass glass-strong" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="eyebrow">Share</div>
            <div className="modal-title">{title}</div>
            {subtitle && <div className="fg-2" style={{ fontSize: 12, marginTop: 4 }}>{subtitle}</div>}
          </div>
          <button className="modal-close" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        {showQR ? (
          <div className="col gap-4" style={{ alignItems: 'center', padding: '20px 0' }}>
            <div className="qr-block"></div>
            <div className="fg-2" style={{ fontSize: 12, textAlign: 'center' }}>Scan to open this playlist on any device</div>
            <button className="btn btn-glass" onClick={() => setShowQR(false)}><Icon name="arrow-left" size={14} /> Back to share</button>
          </div>
        ) : (
          <React.Fragment>
            <div className="share-grid">
              {targets.map(t => (
                <button key={t.key} className="share-btn" onClick={() => handleShare(t.key)}>
                  <div className={`share-ic ${t.cls}`}>{t.svg}</div>
                  <div className="share-lbl">{t.label}</div>
                </button>
              ))}
            </div>
            <div className="share-link-row">
              <Icon name="link" size={14} />
              <code>{url}</code>
              <button className="btn btn-sm btn-ghost" onClick={() => handleShare('cp')}>Copy</button>
            </div>
            <div className="fg-3 mono" style={{ fontSize: 10, marginTop: 12, textAlign: 'center', letterSpacing: '0.08em' }}>
              ANYONE WITH THE LINK CAN VIEW — TOGGLE PRIVATE IN PLAYLIST SETTINGS
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

function CreatePlaylistModal({ open, onClose, onCreate }) {
  const [name, setName] = React.useState('');
  const [emoji, setEmoji] = React.useState('🔥');
  const [isPublic, setIsPublic] = React.useState(true);
  const toast = useToast();
  if (!open) return null;

  const handleCreate = () => {
    if (!name.trim()) return;
    onCreate && onCreate({ name: name + ' ' + emoji, isPublic });
    toast('Playlist created', 'success');
    setName(''); setEmoji('🔥');
    onClose();
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal glass glass-strong" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="eyebrow">New</div>
            <div className="modal-title">Create a playlist</div>
          </div>
          <button className="modal-close" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        <div className="col gap-4">
          <div className="row gap-3" style={{ alignItems: 'flex-start' }}>
            <div style={{
              width: 88, height: 88, borderRadius: 16,
              background: 'linear-gradient(135deg, var(--accent), var(--accent-2))',
              display: 'grid', placeItems: 'center',
              fontSize: 36,
              flexShrink: 0,
            }}>{emoji}</div>
            <div className="col gap-3" style={{ flex: 1 }}>
              <div className="field">
                <label className="field-label">Name</label>
                <input className="input" placeholder="e.g. Late Night Drives" value={name} onChange={e => setName(e.target.value)} autoFocus />
              </div>
              <div className="field">
                <label className="field-label">Cover emoji</label>
                <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
                  {['🔥','🌙','🌊','⚡','💎','🎧','🌌','🎭'].map(e => (
                    <button key={e} className={`chip ${emoji === e ? 'active' : ''}`} onClick={() => setEmoji(e)}>{e}</button>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div className="row gap-3" style={{ padding: '12px 14px', background: 'var(--bg-1)', borderRadius: 14, border: '1px solid var(--line)' }}>
            <Icon name={isPublic ? 'globe' : 'lock'} size={18} />
            <div className="col" style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{isPublic ? 'Public' : 'Private'}</div>
              <div className="fg-2" style={{ fontSize: 11 }}>{isPublic ? 'Anyone with the link can view' : 'Only you can see this playlist'}</div>
            </div>
            <button
              className={`chip ${isPublic ? 'active' : ''}`}
              onClick={() => setIsPublic(p => !p)}
              style={{ width: 44, height: 24, padding: 0, position: 'relative', borderRadius: 999 }}
            >
              <span style={{
                position: 'absolute',
                top: 2, left: isPublic ? 22 : 2,
                width: 18, height: 18,
                borderRadius: '50%',
                background: isPublic ? 'var(--bg-0)' : 'var(--fg-2)',
                transition: 'left 200ms',
              }} />
            </button>
          </div>

          <button className="btn btn-primary btn-block btn-lg" onClick={handleCreate}>
            <Icon name="plus" size={16} /> Create playlist
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ShareModal, CreatePlaylistModal });
