/* global React, TABLES */
const { useState, useMemo, useRef } = React;
const { cx } = window.AS;
const { useNotes } = window.AS_STORE;

// "artist name - table - fandoms [ - note ]" — matches user's requested txt
// shape. If the table has a local note, it's appended with another " - ".
function buildTxt(rows, notes) {
  return rows.map(({ table, artist }) => {
    const fandoms = artist.fandoms.join(', ') || 'none';
    const note = (notes[table.id] || '').trim();
    const base = `${artist.name} - ${table.id} - ${fandoms}`;
    return note ? `${base} - ${note.replace(/\s+/g, ' ')}` : base;
  }).join('\n');
}

function SavedDrawer({ open, onClose, savedIds, onToggleSave, onJumpTo, onClearAll }) {
  const [notes] = useNotes();
  const [copied, setCopied] = useState(false);
  const taRef = useRef(null);

  const savedTables = useMemo(
    () => TABLES.filter(t => savedIds.has(t.id)).sort(
      (a, b) => a.id.localeCompare(b.id, 'en', { numeric: true })
    ),
    [savedIds]
  );

  const rows = useMemo(() => {
    const out = [];
    for (const t of savedTables) for (const a of t.artists) out.push({ table: t, artist: a });
    return out;
  }, [savedTables]);

  const exportText = useMemo(() => buildTxt(rows, notes), [rows, notes]);

  const copyAll = async () => {
    if (!rows.length) return;
    try {
      await navigator.clipboard.writeText(exportText);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch {
      taRef.current?.select();
    }
  };

  return (
    <div className={cx('drawer-root', open && 'is-open')} aria-hidden={!open}>
      <div className="drawer-scrim" onClick={onClose} />
      <aside className="drawer" role="dialog" aria-label="saved tables">
        <div className="drawer-head">
          <h2>saved</h2>
          <button type="button" className="icon-btn close-btn" onClick={onClose} aria-label="close">×</button>
        </div>

        <div className="drawer-body">
          {savedTables.length === 0 ? (
            <div className="empty">
              <div className="empty-big">no saved tables yet</div>
              <div>tap the heart on any table to add it here</div>
            </div>
          ) : (
            <ul className="drawer-list">
              {savedTables.map(t => (
                <li key={t.id} className="drawer-item">
                  <button
                    type="button"
                    className="drawer-row"
                    onClick={() => { onJumpTo && onJumpTo(t.id); onClose(); }}
                  >
                    <span className="drawer-tid">{t.id}</span>
                    <span className="drawer-name">{t.artists.map(a => a.name).join(' · ')}</span>
                    <span className="drawer-fandom">{[...new Set(t.artists.flatMap(a => a.fandoms))].slice(0, 2).join(' · ')}</span>
                  </button>
                  <button
                    type="button"
                    className="icon-btn drawer-unsave"
                    onClick={() => onToggleSave(t.id)}
                    title="remove from saved"
                    aria-label="remove from saved"
                  >♥</button>
                </li>
              ))}
            </ul>
          )}
        </div>

        <div className="drawer-foot">
          <div className="export-label-row">
            <span className="export-label">your list, ready to copy:</span>
            <span className="export-hint">artist - table - fandoms - note</span>
          </div>

          <textarea
            ref={taRef}
            className="export-textarea"
            readOnly
            value={rows.length === 0
              ? 'save a few tables and the text list will show here'
              : exportText}
            onClick={(e) => e.currentTarget.select()}
            aria-label="export text, tap to select all"
          />

          <div className="export-actions">
            <button
              type="button"
              className="btn btn-primary"
              onClick={copyAll}
              disabled={rows.length === 0}
            >
              {copied ? '✓ copied' : 'copy to clipboard'}
            </button>
            {savedTables.length > 0 && (
              <button type="button" className="link danger" onClick={() => { if (confirm('clear all saved tables?')) onClearAll(); }}>
                clear all saved
              </button>
            )}
          </div>
        </div>
      </aside>
    </div>
  );
}

window.SavedDrawer = SavedDrawer;
