// Shell: topbar + left rail + viewport + AI panel + command palette

const MODULES = [
  { id: 'home',   label: 'Home',      letter: '',  color: 'var(--ks-primary)', icon: 'home' },
  { id: 'word',   label: 'Word',      letter: 'W', color: 'var(--mod-word)',   accent: 'word' },
  { id: 'sheets', label: 'Sheets',    letter: 'S', color: 'var(--mod-sheets)', accent: 'sheets' },
  { id: 'slides', label: 'Slides',    letter: 'P', color: 'var(--mod-slides)', accent: 'slides' },
  { id: 'pdf',    label: 'PDF',       letter: 'F', color: 'var(--mod-pdf)',    accent: 'pdf' },
  { id: 'notes',  label: 'Notes',     letter: 'N', color: 'var(--mod-notes)',  accent: 'notes' },
  { id: 'board',  label: 'Board',     letter: 'B', color: 'var(--mod-board)',  accent: 'board' },
  { id: 'db',     label: 'Database',  letter: 'D', color: 'var(--mod-db)',     accent: 'db' },
  { id: 'admin',  label: 'Admin',     letter: '',  color: 'var(--mod-admin)',  icon: 'shieldCheck' },
];

function Topbar({ onSearch, onToggleAI, aiOpen, moduleTitle, moduleAccent }) {
  return (
    <header className="ks-topbar" data-screen-label="topbar">
      <div className="ks-brand">
        <div className="ks-brand-logo">कार्य</div>
        <div className="col" style={{lineHeight: 1.15}}>
          <div className="ks-brand-name">KaryaSuite</div>
          <div className="ks-brand-sub">V3 · Enterprise</div>
        </div>
      </div>

      <div className="ks-org-crumb" title="Organization">
        <span className="dot"/>
        <span>Government of India</span>
        <span style={{color:'var(--ink-400)'}}>·</span>
        <span>MeitY</span>
        {IC.chevronD}
      </div>

      {moduleTitle && (
        <>
          <span style={{color:'var(--ink-300)'}}>/</span>
          <div className="row gap-2" style={{fontSize:13, fontWeight:550, color:'var(--ink-800)'}}>
            <span style={{
              width:16, height:16, borderRadius:4, background: moduleAccent,
              display:'inline-block'
            }}/>
            {moduleTitle}
          </div>
        </>
      )}

      <button className="ks-search" onClick={onSearch}>
        {IC.search}
        <span>Search documents, people, actions…</span>
        <kbd>⌘K</kbd>
      </button>

      <div className="ks-topbar-actions">
        <button className={"ks-icon-btn " + (aiOpen ? 'active' : '')} onClick={onToggleAI} title="AI Assistant">
          {IC.sparkles}
          <span>Karya AI</span>
        </button>
        <button className="ks-icon-btn" title="Notifications">
          {IC.bell}
          <span className="badge"/>
        </button>
        <button className="ks-icon-btn" title="Help">{IC.help}</button>
        <button className="ks-icon-btn" title="Settings">{IC.settings}</button>
        <div className="ks-avatar" title={KS_DATA.user.name}>{KS_DATA.user.initials}</div>
      </div>
    </header>
  );
}

function Rail({ current, onNavigate }) {
  return (
    <nav className="ks-rail" data-screen-label="rail">
      {MODULES.map((m, i) => (
        <React.Fragment key={m.id}>
          <button
            className={"ks-rail-item " + (current === m.id ? 'active' : '')}
            onClick={() => onNavigate(m.id)}
            title={m.label}
          >
            {m.letter ? (
              <div className="mod-swatch" style={{background: m.color}}>{m.letter}</div>
            ) : (
              <div style={{color: current === m.id ? m.color : 'var(--ink-500)'}}>
                {IC[m.icon]}
              </div>
            )}
            <span>{m.label}</span>
          </button>
          {(i === 0 || i === 7) && <div className="ks-rail-divider"/>}
        </React.Fragment>
      ))}
    </nav>
  );
}

// AI panel — contextual to current module
function AIPanel({ open, module, onClose }) {
  const [msgs, setMsgs] = React.useState([
    { role: 'ai', text: 'I can help draft, summarise, translate, or analyse in this workspace. What would you like to do?' },
  ]);
  const [input, setInput] = React.useState('');

  const suggestions = {
    home: ['Summarise my day', 'Draft a status update to my Director', 'Find last week\'s Cabinet Note', 'Translate the DPI Roadmap to Hindi'],
    word: ['Proofread this document', 'Summarise in 5 bullets', 'Translate to हिंदी', 'Suggest a stronger opening paragraph'],
    sheets: ['Explain this formula', 'Generate a formula to compute % utilisation', 'Recommend a chart for this data', 'Find outliers in column D'],
    slides: ['Generate a slide from these notes', 'Suggest speaker notes for slide 3', 'Convert this section into 3 slides', 'Design a summary slide'],
    pdf: ['Extract key clauses', 'Redact PII', 'Compare with previous version', 'Summarise this gazette'],
    notes: ['Turn this note into action items', 'Transcribe last audio note', 'Convert to formal minutes', 'Tag related meetings'],
    board: ['Convert this into a flowchart', 'Cluster these sticky notes', 'Draft a summary from the whiteboard', 'Suggest missing steps'],
    db: ['Write a SQL query for high-priority open cases', 'Explain this table schema', 'Detect anomalies in SLA breaches'],
    admin: ['Draft this month\'s compliance report', 'Find users with elevated access', 'Summarise recent audit events'],
  }[module] || [];

  const send = (text) => {
    const t = (text ?? input).trim();
    if (!t) return;
    setMsgs(m => [...m, { role: 'user', text: t }]);
    setInput('');
    setTimeout(() => {
      setMsgs(m => [...m, { role: 'ai', text: 'Working on it… I will draft a response, cite relevant documents from your workspace, and flag any DPDP-sensitive content before I return the result.' }]);
    }, 420);
  };

  if (!open) return null;

  return (
    <aside className="ai-panel" data-screen-label="ai-panel">
      <div className="ai-panel-header">
        <div className="ai-avatar">K</div>
        <div className="col grow" style={{lineHeight:1.15}}>
          <div style={{fontWeight:600, fontSize:13.5}}>Karya AI</div>
          <div className="muted text-xs">Contextual · {module}</div>
        </div>
        <button className="ks-icon-btn" onClick={onClose}>{IC.x}</button>
      </div>

      <div style={{padding:'10px 14px', borderBottom:'1px solid var(--ink-150)'}}>
        <div className="text-xs muted b-500" style={{marginBottom:6, letterSpacing:'0.04em', textTransform:'uppercase'}}>Suggested</div>
        <div className="row gap-2" style={{flexWrap:'wrap'}}>
          {suggestions.map(s => (
            <button key={s} className="chip purple" style={{cursor:'pointer', border:'1px solid transparent'}}
                    onClick={() => send(s)}>
              {IC.sparkles} {s}
            </button>
          ))}
        </div>
      </div>

      <div className="grow" style={{overflow:'auto', padding: '14px 16px', display:'flex', flexDirection:'column', gap:12}}>
        {msgs.map((m, i) => (
          <div key={i} style={{
            alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
            maxWidth: '86%',
          }}>
            {m.role === 'ai' && (
              <div className="row gap-2" style={{marginBottom:4}}>
                <div className="ai-avatar" style={{width:20, height:20, fontSize:10, borderRadius:5}}>K</div>
                <div className="text-xs muted b-500">Karya AI</div>
              </div>
            )}
            <div style={{
              padding: '9px 12px',
              borderRadius: m.role === 'user' ? '12px 12px 3px 12px' : '3px 12px 12px 12px',
              background: m.role === 'user' ? 'var(--ks-primary)' : 'var(--ink-100)',
              color: m.role === 'user' ? 'white' : 'var(--ink-800)',
              fontSize: 13,
              lineHeight: 1.5,
            }}>
              {m.text}
            </div>
          </div>
        ))}
      </div>

      <div style={{padding:12, borderTop:'1px solid var(--ink-150)'}}>
        <div style={{
          display:'flex', alignItems:'flex-end', gap:6,
          padding:'8px 10px', border:'1px solid var(--ink-200)', borderRadius:12,
          background: 'var(--white)',
        }}>
          <textarea
            rows={1}
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
            placeholder="Ask Karya AI…"
            style={{
              flex:1, border:'none', outline:'none', resize:'none',
              background:'transparent', fontSize:13, lineHeight:1.4, minHeight:20,
              padding: '2px 0', maxHeight: 120,
            }}
          />
          <button className="ks-icon-btn" title="Voice">{IC.mic}</button>
          <button className="btn ai" onClick={() => send()} style={{height:28, padding:'0 10px'}}>
            {IC.send} Send
          </button>
        </div>
        <div className="text-xs muted" style={{marginTop:8, display:'flex', gap:10}}>
          <span className="row gap-2">{IC.shieldCheck} On-premise · DPDP compliant</span>
          <span className="row gap-2">{IC.cloud} Model: Karya-8B (local)</span>
        </div>
      </div>
    </aside>
  );
}

// Command palette
function CommandPalette({ open, onClose, onNavigate }) {
  const [q, setQ] = React.useState('');
  const inputRef = React.useRef(null);
  React.useEffect(() => { if (open) setTimeout(() => inputRef.current?.focus(), 30); }, [open]);
  React.useEffect(() => { if (!open) setQ(''); }, [open]);

  const items = [
    ...MODULES.filter(m => m.id !== 'home').map(m => ({ kind:'nav', id:m.id, label:'Go to ' + m.label, hint:'Module', color:m.color })),
    { kind:'action', id:'new-doc',   label:'New Word document',      hint:'Create', color:'var(--mod-word)' },
    { kind:'action', id:'new-sheet', label:'New Spreadsheet',        hint:'Create', color:'var(--mod-sheets)' },
    { kind:'action', id:'new-deck',  label:'New Presentation',       hint:'Create', color:'var(--mod-slides)' },
    { kind:'action', id:'new-note',  label:'New Note',               hint:'Create', color:'var(--mod-notes)' },
    { kind:'action', id:'ai-summ',   label:'AI: Summarise this document', hint:'AI', color:'var(--mod-ai)' },
    { kind:'action', id:'ai-trans',  label:'AI: Translate to हिंदी',   hint:'AI', color:'var(--mod-ai)' },
    ...KS_DATA.recentDocs.slice(0,6).map(d => ({ kind:'doc', id:d.id, label:d.title, hint:'Recent · '+d.owner, color:'var(--mod-'+d.mod+')' })),
  ];
  const filtered = q ? items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())) : items;

  if (!open) return null;
  return (
    <div className="cmd-overlay" onClick={onClose}>
      <div className="cmd-box" onClick={e => e.stopPropagation()}>
        <div style={{padding:'12px 14px', display:'flex', gap:10, alignItems:'center', borderBottom:'1px solid var(--ink-150)'}}>
          <div style={{color:'var(--ink-500)'}}>{IC.search}</div>
          <input ref={inputRef} value={q} onChange={e=>setQ(e.target.value)}
                 placeholder="Search modules, documents, people, actions…"
                 style={{flex:1, border:'none', outline:'none', fontSize:15, background:'transparent'}}
                 onKeyDown={e => { if (e.key === 'Escape') onClose(); }}/>
          <kbd style={{background:'var(--ink-100)', padding:'2px 6px', borderRadius:4, fontFamily:'var(--f-mono)', fontSize:11, color:'var(--ink-600)'}}>Esc</kbd>
        </div>
        <div style={{maxHeight:'52vh', overflow:'auto', padding: '8px 6px'}}>
          {filtered.slice(0,12).map(item => (
            <button key={item.kind+item.id} className="row gap-3"
                    onClick={() => {
                      if (item.kind === 'nav') onNavigate(item.id);
                      onClose();
                    }}
                    style={{
                      width:'100%', textAlign:'left',
                      padding: '9px 12px', border:'none', background:'transparent',
                      borderRadius: 8,
                    }}
                    onMouseEnter={e => e.currentTarget.style.background='var(--ink-100)'}
                    onMouseLeave={e => e.currentTarget.style.background='transparent'}>
              <div style={{width:26, height:26, borderRadius:6, background:item.color, opacity:0.15}}/>
              <div className="col grow" style={{marginLeft: -22}}>
                <div style={{fontSize:13.5, fontWeight:500}}>{item.label}</div>
              </div>
              <div className="chip">{item.hint}</div>
            </button>
          ))}
          {filtered.length === 0 && <div className="muted text-sm" style={{padding:20}}>No matches.</div>}
        </div>
        <div style={{padding:'8px 14px', borderTop:'1px solid var(--ink-150)', display:'flex', gap:14, fontSize:11, color:'var(--ink-500)'}}>
          <span><kbd className="mono">↑↓</kbd> navigate</span>
          <span><kbd className="mono">↵</kbd> select</span>
          <span><kbd className="mono">esc</kbd> close</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Topbar, Rail, AIPanel, CommandPalette, MODULES });
