/* global React */
const { useState, useRef, useEffect } = React;

const HEADER_DOMAINS = [
  { id: 'inner',         label: 'Inner World',    color: 'var(--axis-inner)'         },
  { id: 'physical',      label: 'Physical',       color: 'var(--axis-physical)'      },
  { id: 'creative',      label: 'Creative',       color: 'var(--axis-creative)'      },
  { id: 'interpersonal', label: 'Interpersonal',  color: 'var(--axis-interpersonal)' },
  { id: 'adventure',     label: 'Adventure',      color: 'var(--axis-adventure)'     },
  { id: 'admin',         label: 'Life Admin',     color: 'var(--axis-life-admin)'    },
];

const NEW_ENTRY_OPTIONS = [
  { id: 'action',   label: 'Action'    },
  { id: 'practice', label: 'Practice'  },
  { id: 'log',      label: 'Daily Log' },
];

/* ── Shared drawer hook ──────────────────────────────────────────────────── */
function useDrawer(drawerRef, onClose) {
  useEffect(() => {
    const onMouse = (e) => {
      if (drawerRef.current && !drawerRef.current.contains(e.target)) onClose();
    };
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('mousedown', onMouse);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onMouse);
      document.removeEventListener('keydown', onKey);
    };
  }, [onClose]);
}

/* ── ActionDrawer ────────────────────────────────────────────────────────── */
const ActionDrawer = ({ onClose }) => {
  const [title,  setTitle]  = useState('');
  const [desc,   setDesc]   = useState('');
  const [saving, setSaving] = useState(false);
  const drawerRef = useRef(null);
  const titleRef  = useRef(null);

  useDrawer(drawerRef, onClose);
  useEffect(() => { titleRef.current?.focus(); }, []);

  const handleSubmit = () => {
    if (!title.trim() || saving) return;
    setSaving(true);
    fetch('/api/actions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ai_refined_title: title.trim(),
        ai_refined_description: desc.trim() || null,
        origin_snippet: title.trim(),
        domain: 'admin',
        score: 0.55,
        horizon_state: 'focus_zone',
      }),
    })
      .then(() => {
        window.dispatchEvent(new CustomEvent('soulitics:board-refresh'));
        setSaving(false);
        onClose();
      })
      .catch(() => setSaving(false));
  };

  return (
    <>
      <div className="drawer-backdrop" aria-hidden="true" />
      <aside className="detail-drawer" role="dialog" aria-modal="true" aria-label="New Action" ref={drawerRef}>
        <div className="detail-drawer__inner">
          <div className="detail-drawer__topbar detail-drawer__topbar--pinned">
            <span className="detail-drawer__eyebrow">NEW ACTION</span>
            <button className="detail-drawer__close" onClick={onClose} aria-label="Close">x</button>
          </div>
          <div className="detail-drawer__scroll-body">
            <div className="detail-drawer__zone">
              <div className="detail-drawer__field">
                <label className="detail-drawer__label">Action Name <span style={{color:'var(--gold-1)',fontSize:'10px'}}>required</span></label>
                <input
                  ref={titleRef}
                  className="detail-drawer__input"
                  placeholder="What requires execution?"
                  value={title}
                  onChange={e => setTitle(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) handleSubmit(); }}
                />
              </div>
              <div className="detail-drawer__field">
                <label className="detail-drawer__label">Description <span style={{color:'var(--ink-3)',fontSize:'10px'}}>optional</span></label>
                <textarea
                  className="detail-drawer__textarea"
                  placeholder="Context, constraints, or resonance..."
                  value={desc}
                  onChange={e => setDesc(e.target.value)}
                  rows={4}
                />
              </div>
            </div>
          </div>
          <div className="detail-drawer__footer-bar">
            <button className="btn-secondary" onClick={onClose}>Cancel</button>
            <button className="btn-primary" onClick={handleSubmit} disabled={!title.trim() || saving}>
              {saving ? 'Saving...' : 'Add Action'}
            </button>
          </div>
        </div>
      </aside>
    </>
  );
};

/* ── DailyLogDrawer ──────────────────────────────────────────────────────── */
const DailyLogDrawer = ({ onClose }) => {
  const [text, setText]     = useState('');
  const [saving, setSaving] = useState(false);
  const drawerRef   = useRef(null);
  const textareaRef = useRef(null);

  useDrawer(drawerRef, onClose);
  useEffect(() => { textareaRef.current?.focus(); }, []);

  const handleSubmit = () => {
    const body = text.trim();
    if (!body || saving) return;
    setSaving(true);
    fetch('/api/actions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ai_refined_title: body.slice(0, 80),
        ai_refined_description: body,
        origin_snippet: body.slice(0, 80),
        domain: 'inner',
        score: 0.55,
        horizon_state: 'focus_zone',
      }),
    })
      .then(() => { window.dispatchEvent(new CustomEvent('soulitics:board-refresh')); setSaving(false); onClose(); })
      .catch(() => setSaving(false));
  };

  return (
    <>
      <div className="drawer-backdrop" aria-hidden="true" />
      <aside className="detail-drawer" role="dialog" aria-modal="true" aria-label="Daily Log" ref={drawerRef}>
        <div className="detail-drawer__inner">
          <div className="detail-drawer__topbar detail-drawer__topbar--pinned">
            <span className="detail-drawer__eyebrow">DAILY LOG</span>
            <button className="detail-drawer__close" onClick={onClose} aria-label="Close">x</button>
          </div>
          <div className="detail-drawer__scroll-body">
            <div className="detail-drawer__zone">
              <textarea
                ref={textareaRef}
                className="daily-log-drawer__textarea"
                placeholder="Log your rhythm..."
                value={text}
                onChange={e => setText(e.target.value)}
                rows={10}
              />
            </div>
          </div>
          <div className="detail-drawer__footer-bar">
            <button className="btn-secondary" onClick={onClose}>Cancel</button>
            <button className="btn-primary" onClick={handleSubmit} disabled={!text.trim() || saving}>
              {saving ? 'Saving...' : 'Log Entry'}
            </button>
          </div>
        </div>
      </aside>
    </>
  );
};

/* ── Header ──────────────────────────────────────────────────────────────── */
const Header = ({ activeDomains, onDomainClick }) => {
  const [menuOpen,         setMenuOpen]         = useState(false);
  const [showAction,       setShowAction]       = useState(false);
  const [showDailyLog,     setShowDailyLog]     = useState(false);
  const [showPracticeForm, setShowPracticeForm] = useState(false);
  const [practiceRegistry, setPracticeRegistry] = useState([]);
  const menuRef    = useRef(null);
  const triggerRef = useRef(null);
  const itemRefs   = useRef([]);

  useEffect(() => {
    const onMouse = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false);
    };
    document.addEventListener('mousedown', onMouse);
    return () => document.removeEventListener('mousedown', onMouse);
  }, []);

  useEffect(() => {
    if (menuOpen) itemRefs.current[0]?.focus();
  }, [menuOpen]);

  const handleMenuKeyDown = (e) => {
    const items = itemRefs.current.filter(Boolean);
    const idx   = items.indexOf(document.activeElement);
    if (e.key === 'Escape')    { e.preventDefault(); setMenuOpen(false); triggerRef.current?.focus(); }
    if (e.key === 'ArrowDown') { e.preventDefault(); items[(idx + 1) % items.length]?.focus(); }
    if (e.key === 'ArrowUp')   { e.preventDefault(); items[(idx - 1 + items.length) % items.length]?.focus(); }
  };

  const handleSelect = (type) => {
    setMenuOpen(false);
    if (type === 'action') {
      setShowAction(true);
    } else if (type === 'practice') {
      fetch('/api/momentum/registry')
        .then(r => r.ok ? r.json() : [])
        .then(reg => { setPracticeRegistry(reg); setShowPracticeForm(true); })
        .catch(() => { setPracticeRegistry([]); setShowPracticeForm(true); });
    } else {
      setShowDailyLog(true);
    }
  };

  return (
    <>
      <header className="app-header">
        <div className="app-header__domains" role="group" aria-label="Filter by domain">
          <button
            className={'app-header__domain-pill app-header__domain-pill--all' + (activeDomains.length === 0 ? ' is-active' : '')}
            type="button"
            onClick={() => onDomainClick(null)}
            aria-pressed={activeDomains.length === 0}
          >
            All Life Domains
          </button>
          {HEADER_DOMAINS.map(d => (
            <button
              key={d.id}
              className={'app-header__domain-pill' + (activeDomains.includes(d.id) ? ' is-active' : '')}
              type="button"
              onClick={() => onDomainClick(d.id)}
              aria-pressed={activeDomains.includes(d.id)}
            >
              <span className="app-header__domain-dot" style={{ background: d.color }} aria-hidden="true" />
              {d.label}
            </button>
          ))}
        </div>

        <div className="app-header__right">
          <button className="app-header__bell" aria-label="Notifications" title="Notifications">
            <span className="app-header__bell-ico" aria-hidden="true" />
          </button>

          <div className="app-header__entry-wrap" ref={menuRef}>
            <button
              ref={triggerRef}
              className="btn-primary app-header__entry-btn"
              onClick={() => setMenuOpen(v => !v)}
              aria-expanded={menuOpen}
              aria-haspopup="menu"
              aria-controls="new-entry-menu"
            >
              + New Entry
            </button>
            {menuOpen && (
              <div
                id="new-entry-menu"
                className="new-entry-menu"
                role="menu"
                onKeyDown={handleMenuKeyDown}
              >
                {NEW_ENTRY_OPTIONS.map((opt, i) => (
                  <button
                    key={opt.id}
                    ref={el => { itemRefs.current[i] = el; }}
                    className="new-entry-menu__item"
                    role="menuitem"
                    tabIndex={-1}
                    onClick={() => handleSelect(opt.id)}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      </header>

      {showAction && (
        <ActionDrawer onClose={() => setShowAction(false)} />
      )}
      {showDailyLog && (
        <DailyLogDrawer onClose={() => setShowDailyLog(false)} />
      )}
      {showPracticeForm && window.LogEntryForm && React.createElement(window.LogEntryForm, {
        registry: practiceRegistry,
        onClose: () => setShowPracticeForm(false),
        onSave: ({ practice_id, date, source }) => {
          fetch('/api/practice/log', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ practice_id, date, source }),
          })
            .then(() => window.dispatchEvent(new CustomEvent('soulitics:board-refresh')))
            .catch(() => {});
          setShowPracticeForm(false);
        },
      })}
    </>
  );
};

/* ── Sidebar ─────────────────────────────────────────────────────────────── */
const Sidebar = () => (
  <aside className="sidebar">
    <div className="sidebar__lock">
      <h1>SOULITICS</h1>
      <p>Cartographer's Console</p>
    </div>
    <nav className="sidenav">
      <a href="/dashboard-ui/" className="sidenav__item is-active">
        <span className="l">
          <span className="sidenav__ico" style={{"--ico": "url(/dashboard-ui/assets/icons/dashboard.svg)"}} />
          <span className="sidenav__lbl">Dashboard</span>
        </span>
        <span className="dot" />
      </a>
      <a href="/dashboard-ui/map" className="sidenav__item">
        <span className="l">
          <span className="sidenav__ico" style={{"--ico": "url(/dashboard-ui/assets/icons/star-maps.svg)"}} />
          <span className="sidenav__lbl">Alignment Map</span>
        </span>
      </a>
      <a className="sidenav__item" aria-disabled="true" title="Coming soon" style={{opacity:0.45,cursor:'default',pointerEvents:'none'}}>
        <span className="l">
          <span className="sidenav__ico" style={{"--ico": "url(/dashboard-ui/assets/icons/manuscripts.svg)"}} />
          <span className="sidenav__lbl">Weekly Review</span>
        </span>
      </a>
      <a className="sidenav__item" aria-disabled="true" title="Coming soon" style={{opacity:0.45,cursor:'default',pointerEvents:'none'}}>
        <span className="l">
          <span className="sidenav__ico" style={{"--ico": "url(/dashboard-ui/assets/icons/book.svg)"}} />
          <span className="sidenav__lbl">Monthly Review</span>
        </span>
      </a>
      <a className="sidenav__item" aria-disabled="true" title="Coming soon" style={{opacity:0.45,cursor:'default',pointerEvents:'none'}}>
        <span className="l">
          <span className="sidenav__ico" style={{"--ico": "url(/dashboard-ui/assets/icons/star-maps.svg)"}} />
          <span className="sidenav__lbl">Quarterly Review</span>
        </span>
      </a>
    </nav>
    <div className="sidebar__footer">
      <a className="sidenav__item" aria-disabled="true" title="Coming soon" style={{opacity:0.45,cursor:'default',pointerEvents:'none'}}>
        <span className="l">
          <span className="sidenav__ico" style={{"--ico": "url(/dashboard-ui/assets/icons/settings.svg)"}} />
          <span className="sidenav__lbl">Settings</span>
        </span>
      </a>
      <a className="sidenav__item" aria-disabled="true" title="Coming soon" style={{opacity:0.45,cursor:'default',pointerEvents:'none'}}>
        <span className="l">
          <span className="sidenav__ico" style={{"--ico": "url(/dashboard-ui/assets/icons/support.svg)"}} />
          <span className="sidenav__lbl">Support</span>
        </span>
      </a>
    </div>
  </aside>
);

/* ── DashboardShell ──────────────────────────────────────────────────────── */
const DashboardShell = () => {
  const [activeDomains, setActiveDomains] = useState([]);

  const handleDomainClick = (domainId) => {
    setActiveDomains(prev => {
      let next;
      if (domainId === null) next = [];                                  // All Life Domains
      else if (prev.includes(domainId)) next = prev.filter(d => d !== domainId);
      else next = [...prev, domainId];
      window.dispatchEvent(new CustomEvent('soulitics:domain-filter', { detail: { domains: next } }));
      return next;
    });
  };

  return (
    <div className="app-shell app-shell--dash2">
      <Sidebar />
      <main className="main-content main-content--dash2">
        <Header activeDomains={activeDomains} onDomainClick={handleDomainClick} />
        <div className="view-container view-container--dash2">
          <div className="dashboard-stage dashboard-stage--dash2">
            {React.createElement(window.ActionStream)}
          </div>
        </div>
      </main>
    </div>
  );
};

window.DashboardShell = DashboardShell;
