// Primus IQ — SharePoint Picker Modal

const spFmtSize = (bytes) => {
  const b = bytes || 0;
  return b < 1024 ? `${b} B`
       : b < 1048576 ? `${(b / 1024).toFixed(1)} KB`
       : `${(b / 1048576).toFixed(1)} MB`;
};

const SharePointPickerModal = ({ open, onClose, onConfirm }) => {
  const [tab, setTab] = React.useState('onedrive');     // 'onedrive' | 'sharepoint'
  const [siteQuery, setSiteQuery] = React.useState('');
  const [sites, setSites] = React.useState([]);
  const [selectedSite, setSelectedSite] = React.useState(null);
  const [drives, setDrives] = React.useState([]);
  const [drive, setDrive] = React.useState(null);        // active drive being browsed
  const [path, setPath] = React.useState([]);            // breadcrumb: [{id, name}]
  const [items, setItems] = React.useState([]);
  const [selected, setSelected] = React.useState({});    // itemId -> {drive_id, item_id, name, size}
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const fail = (ex) => { setError(ex && ex.message ? ex.message : 'Something went wrong'); setLoading(false); };

  // ── OneDrive: open the user's drive directly ──
  const openOneDrive = async () => {
    setTab('onedrive'); setSelectedSite(null); setDrives([]); setSites([]); setSiteQuery(''); setError('');
    setLoading(true);
    try {
      const d = await PrimusAPI.spOneDrive();
      setDrive(d);
      setPath([{ id: null, name: d.name || 'OneDrive' }]);
      const its = await PrimusAPI.spListItems(d.id, null);
      setItems(its || []); setLoading(false);
    } catch (ex) { fail(ex); }
  };

  // ── SharePoint: switch tab and auto-load accessible sites ──
  const switchToSharePoint = async () => {
    setTab('sharepoint'); setDrive(null); setSelectedSite(null); setDrives([]);
    setPath([]); setItems([]); setError(''); setSites([]);
    setLoading(true);
    try {
      const res = await PrimusAPI.spSearchSites(siteQuery);
      setSites(res || []); setLoading(false);
    } catch (ex) { fail(ex); }
  };

  // ── SharePoint: refine site search ──
  const runSiteSearch = async () => {
    setLoading(true); setError('');
    try {
      const res = await PrimusAPI.spSearchSites(siteQuery);
      setSites(res || []); setLoading(false);
    } catch (ex) { fail(ex); }
  };

  // Auto-load OneDrive when the modal opens. Reset the selection + breadcrumb
  // first: the component stays mounted while closed, so without this a re-open
  // carries over items already imported in a previous session — they'd be
  // re-selected and re-sent to tagging alongside the new pick.
  React.useEffect(() => {
    if (open) { setSelected({}); setPath([]); openOneDrive(); }
  }, [open]);

  const pickSite = async (site) => {
    setSelectedSite(site); setDrive(null); setPath([]); setItems([]); setError('');
    setLoading(true);
    try {
      const ds = await PrimusAPI.spListDrives(site.id);
      setDrives(ds || []); setLoading(false);
    } catch (ex) { fail(ex); }
  };

  const pickDrive = async (d) => {
    setDrive(d); setPath([{ id: null, name: d.name }]); setError('');
    setLoading(true);
    try {
      const its = await PrimusAPI.spListItems(d.id, null);
      setItems(its || []); setLoading(false);
    } catch (ex) { fail(ex); }
  };

  const openFolder = async (folder) => {
    setError(''); setLoading(true);
    try {
      const its = await PrimusAPI.spListItems(drive.id, folder.id);
      setPath(prev => [...prev, { id: folder.id, name: folder.name }]);
      setItems(its || []); setLoading(false);
    } catch (ex) { fail(ex); }
  };

  const goToCrumb = async (idx) => {
    const crumb = path[idx];
    setError(''); setLoading(true);
    try {
      const its = await PrimusAPI.spListItems(drive.id, crumb.id);
      setPath(prev => prev.slice(0, idx + 1));
      setItems(its || []); setLoading(false);
    } catch (ex) { fail(ex); }
  };

  const toggleFile = (item) => {
    setSelected(prev => {
      const next = { ...prev };
      if (next[item.id]) delete next[item.id];
      else next[item.id] = { drive_id: drive.id, item_id: item.id, name: item.name, size: item.size };
      return next;
    });
  };

  const selectedList = Object.values(selected);

  const confirm = () => {
    if (selectedList.length === 0) return;
    onConfirm(selectedList);
  };

  if (!open) return null;

  const showBrowser = !!drive;
  const showSiteList = tab === 'sharepoint' && !selectedSite;
  const showDriveList = tab === 'sharepoint' && selectedSite && !drive;

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 70,
      background: 'var(--bg-overlay)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      animation: 'fadein 0.18s ease-out',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 920, maxWidth: '94%', height: 620, maxHeight: '92%',
        background: 'var(--bg-card)', borderRadius: 18,
        boxShadow: 'var(--shadow-lg), 0 0 0 1px var(--line)',
        animation: 'rise 0.22s ease-out',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{
          padding: '18px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          borderBottom: '1px solid var(--line)',
        }}>
          <div>
            <h2 className="serif" style={{ fontSize: 18, fontWeight: 500, margin: 0, letterSpacing: '-0.01em' }}>Add from Microsoft 365</h2>
            <div style={{ fontSize: 13, color: 'var(--mute)', marginTop: 3 }}>
              Browse your OneDrive or SharePoint and pick files to import.
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 30, height: 30, borderRadius: 8, background: 'transparent', border: 'none',
            cursor: 'pointer', display: 'grid', placeItems: 'center', color: 'var(--mute)',
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
        </div>

        {/* Source tabs */}
        <div style={{ display: 'flex', gap: 8, padding: '12px 24px 0' }}>
          <button onClick={openOneDrive} style={spTabStyle(tab === 'onedrive')}>OneDrive</button>
          <button onClick={switchToSharePoint} style={spTabStyle(tab === 'sharepoint')}>SharePoint sites</button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', padding: '14px 24px' }}>
          {/* Site search */}
          {showSiteList && (
            <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
              <input
                value={siteQuery}
                onChange={e => setSiteQuery(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter') runSiteSearch(); }}
                placeholder="Search SharePoint sites by name…"
                style={{
                  flex: 1, height: 38, padding: '0 12px', borderRadius: 9,
                  border: '1px solid var(--line-2)', fontSize: 13, fontFamily: 'inherit',
                  outline: 'none', color: 'var(--ink)', background: 'var(--bg-card)',
                }}
              />
              <button onClick={runSiteSearch} className="btn-primary" style={{ height: 38 }}>Search</button>
            </div>
          )}

          {/* Breadcrumbs when browsing */}
          {showBrowser && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 12, fontSize: 13 }}>
              {selectedSite && (
                <>
                  <button onClick={() => { setDrive(null); setItems([]); setPath([]); }} style={spCrumbBtn}>{selectedSite.display_name}</button>
                  <span style={{ color: 'var(--mute-2)' }}>/</span>
                </>
              )}
              {path.map((c, i) => (
                <React.Fragment key={`${c.id || 'root'}-${i}`}>
                  {i > 0 && <span style={{ color: 'var(--mute-2)' }}>/</span>}
                  <button onClick={() => goToCrumb(i)} style={{ ...spCrumbBtn, color: i === path.length - 1 ? 'var(--ink)' : 'var(--maroon)', fontWeight: i === path.length - 1 ? 600 : 500 }}>{c.name}</button>
                </React.Fragment>
              ))}
            </div>
          )}

          {error && (
            <div style={{ padding: '10px 12px', borderRadius: 9, background: 'var(--maroon-wash)', border: '1px solid var(--maroon-10)', color: 'var(--maroon)', fontSize: 12, marginBottom: 12 }}>
              {error}
            </div>
          )}

          {/* List area */}
          <div style={{ flex: 1, overflow: 'auto', border: '1px solid var(--line)', borderRadius: 12, background: 'var(--bg-card)' }}>
            {loading && <div style={spEmpty}>Loading…</div>}

            {/* Site results */}
            {!loading && showSiteList && sites.length === 0 && <div style={spEmpty}>No accessible SharePoint sites found.</div>}
            {!loading && showSiteList && sites.map(s => (
              <div key={s.id} onClick={() => pickSite(s)} style={spRow}>
                <SpIcon kind="site" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={spName}>{s.display_name}</div>
                  {s.web_url && <div style={spSub}>{s.web_url}</div>}
                </div>
                <span style={{ color: 'var(--mute-2)' }}>›</span>
              </div>
            ))}

            {/* Drive (library) list */}
            {!loading && showDriveList && drives.length === 0 && <div style={spEmpty}>No document libraries on this site.</div>}
            {!loading && showDriveList && drives.map(d => (
              <div key={d.id} onClick={() => pickDrive(d)} style={spRow}>
                <SpIcon kind="library" />
                <div style={{ flex: 1, minWidth: 0 }}><div style={spName}>{d.name}</div></div>
                <span style={{ color: 'var(--mute-2)' }}>›</span>
              </div>
            ))}

            {/* File / folder browser */}
            {!loading && showBrowser && items.length === 0 && <div style={spEmpty}>This folder is empty.</div>}
            {!loading && showBrowser && items.map(it => {
              const checked = !!selected[it.id];
              if (it.is_folder) {
                return (
                  <div key={it.id} onClick={() => openFolder(it)} style={spRow}>
                    <SpIcon kind="folder" />
                    <div style={{ flex: 1, minWidth: 0 }}><div style={spName}>{it.name}</div></div>
                    <span style={{ color: 'var(--mute-2)' }}>›</span>
                  </div>
                );
              }
              return (
                <div key={it.id} onClick={() => toggleFile(it)} style={{ ...spRow, background: checked ? 'var(--maroon-06)' : 'transparent' }}>
                  <div style={{
                    width: 18, height: 18, borderRadius: 5, flexShrink: 0,
                    border: `1.5px solid ${checked ? 'var(--maroon)' : 'var(--line-2)'}`,
                    background: checked ? 'var(--maroon)' : 'var(--bg-card)',
                    display: 'grid', placeItems: 'center',
                  }}>
                    {checked && <svg width="11" height="11" viewBox="0 0 12 12"><path d="M2 6.5l2.5 2.5L10 3.5" stroke="white" fill="none" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                  </div>
                  <SpIcon kind="file" />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={spName}>{it.name}</div>
                    <div style={spSub}>{spFmtSize(it.size)}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Footer */}
        <div style={{
          padding: '14px 24px', borderTop: '1px solid var(--line)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: 'var(--bg-card)',
        }}>
          <span style={{ fontSize: 13, color: 'var(--mute)' }}>
            {selectedList.length > 0 ? `${selectedList.length} file${selectedList.length > 1 ? 's' : ''} selected` : 'No files selected'}
          </span>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={onClose} className="btn-secondary" style={{ height: 36 }}>Cancel</button>
            <button onClick={confirm} disabled={selectedList.length === 0} className="btn-primary" style={{ height: 36, opacity: selectedList.length === 0 ? 0.5 : 1 }}>
              Add {selectedList.length || ''} file{selectedList.length === 1 ? '' : 's'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

const SpIcon = ({ kind }) => {
  const color = kind === 'site' ? 'var(--maroon)' : kind === 'library' ? 'var(--gold)' : kind === 'folder' ? 'var(--gold)' : 'var(--mute)';
  const paths = {
    site:    <path d="M3 21V7l9-4 9 4v14M3 21h18M9 21v-6h6v6" stroke={color} strokeWidth="1.6" fill="none" strokeLinejoin="round"/>,
    library: <path d="M4 5h16v14H4zM4 9h16M9 5v14" stroke={color} strokeWidth="1.6" fill="none" strokeLinejoin="round"/>,
    folder:  <path d="M3 6a1 1 0 0 1 1-1h5l2 2h8a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z" stroke={color} strokeWidth="1.6" fill="none" strokeLinejoin="round"/>,
    file:    <path d="M6 2h8l4 4v16H6zM14 2v4h4" stroke={color} strokeWidth="1.6" fill="none" strokeLinejoin="round"/>,
  };
  return <svg width="20" height="20" viewBox="0 0 24 24" style={{ flexShrink: 0 }}>{paths[kind]}</svg>;
};

const spTabStyle = (active) => ({
  height: 34, padding: '0 16px', borderRadius: '9px 9px 0 0', cursor: 'pointer',
  fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
  border: '1px solid var(--line)', borderBottom: active ? '1px solid var(--bg-card)' : '1px solid var(--line)',
  background: active ? 'var(--bg-card)' : 'var(--bg-soft)',
  color: active ? 'var(--maroon)' : 'var(--mute)',
  position: 'relative', top: 1,
});
const spRow = {
  display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px',
  borderBottom: '1px solid var(--line)', cursor: 'pointer',
};
const spName = { fontSize: 13, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' };
const spSub = { fontSize: 11, color: 'var(--mute)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' };
const spCrumbBtn = { background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, color: 'var(--maroon)', padding: 0 };
const spEmpty = { padding: '48px 20px', textAlign: 'center', color: 'var(--mute)', fontSize: 13 };

Object.assign(window, {
  SharePointPickerModal,
  SpIcon,
});
