// Editor — the main design workspace. Top bar, left tool rail, canvas, right panels, bottom status bar.

const TOOLS = [
  { key: 'select',  icon: I.pointer,   name: 'Select',      shortcut: 'V' },
  { key: 'pen',     icon: I.pen,       name: 'Pen',         shortcut: 'P' },
  { key: 'shape',   icon: I.shape,     name: 'Shape',       shortcut: 'R' },
  { key: 'text',    icon: I.text,      name: 'Text',        shortcut: 'T' },
  { key: 'brush',   icon: I.brush,     name: 'Brush',       shortcut: 'B' },
  { key: 'image',   icon: I.image,     name: 'Place Image', shortcut: 'I' },
  { key: 'crop',    icon: I.crop,      name: 'Crop',        shortcut: 'C' },
  { key: 'frame',   icon: I.frame,     name: 'Frame',       shortcut: 'F' },
  { key: 'eyedrop', icon: I.eyedropper,name: 'Eyedropper',  shortcut: 'K' },
  { key: 'zoom',    icon: I.zoom,      name: 'Zoom',        shortcut: 'Z' },
  { key: 'hand',    icon: I.hand,      name: 'Hand',        shortcut: 'H' },
];

const RIGHT_TABS = [
  { key: 'props',   name: 'Properties', icon: I.settings },
  { key: 'layers',  name: 'Layers',     icon: I.layers },
  { key: 'brand',   name: 'Brand Kit',  icon: I.brand },
  { key: 'ai',      name: 'AI Assist',  icon: I.sparkle },
  { key: 'history', name: 'History',    icon: I.history },
];

function Editor({ onExit, onOpenApproval, onOpenExport }) {
  const [tool, setTool] = React.useState('select');
  const [zoom, setZoom] = React.useState(1.0);
  const [selectedId, setSelectedId] = React.useState('schedule');
  const [rightTab, setRightTab] = React.useState('props');
  const [showGrid, setShowGrid] = React.useState(true);
  const [showGuides, setShowGuides] = React.useState(true);
  const [showBleed, setShowBleed] = React.useState(false);
  const [file, setFile] = React.useState('Tender Notice — Rural Development');

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--bg-panel)' }}>
      <EditorTopBar
        file={file} setFile={setFile}
        onExit={onExit}
        onOpenApproval={onOpenApproval}
        onOpenExport={onOpenExport}
      />
      <EditorToolbar
        tool={tool}
        selectedId={selectedId}
        zoom={zoom} setZoom={setZoom}
        showGrid={showGrid} setShowGrid={setShowGrid}
        showGuides={showGuides} setShowGuides={setShowGuides}
        showBleed={showBleed} setShowBleed={setShowBleed}
      />
      <div style={{ display: 'flex', flex: 1, minHeight: 0 }}>
        <ToolRail tool={tool} setTool={setTool} />
        <DesignCanvas
          zoom={zoom}
          selectedId={selectedId}
          onSelect={setSelectedId}
          showGrid={showGrid}
          showGuides={showGuides}
          showBleed={showBleed}
        />
        <RightRail rightTab={rightTab} setRightTab={setRightTab} />
        <div style={{ width: 'var(--panel-w)', borderLeft: '1px solid var(--line)', background: 'var(--bg-panel)', overflow: 'auto' }}>
          {rightTab === 'props'   && <PropertiesPanel selectedId={selectedId}/>}
          {rightTab === 'layers'  && <LayersPanel selectedId={selectedId} onSelect={setSelectedId}/>}
          {rightTab === 'brand'   && <BrandKitPanel/>}
          {rightTab === 'ai'      && <AIAssistPanel/>}
          {rightTab === 'history' && <HistoryPanel/>}
        </div>
      </div>
      <StatusBar selectedId={selectedId} tool={tool} zoom={zoom}/>
    </div>
  );
}

// ============ TOP BAR ============
function EditorTopBar({ file, setFile, onExit, onOpenApproval, onOpenExport }) {
  const [editing, setEditing] = React.useState(false);
  return (
    <div style={{ height: 'var(--topbar-h)', borderBottom: '1px solid var(--line)', background: 'var(--bg-panel)', display: 'flex', alignItems: 'center', padding: '0 12px', gap: 12 }}>
      {/* Left: logo + breadcrumb */}
      <Row gap={10}>
        <button onClick={onExit} style={{ padding: '2px 4px', display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer', background: 'none', border: 'none' }} title="Back to workspace">
          <Logo size={20}/>
        </button>
        <Row gap={6} style={{ fontSize: 12 }}>
          <button onClick={onExit} className="mono" style={{ color: 'var(--ink-muted)', letterSpacing: '0.02em', cursor: 'pointer', background: 'none', border: 'none' }}>MoRD</button>
          <span style={{ color: 'var(--ink-subtle)' }}>/</span>
          <button onClick={onExit} style={{ color: 'var(--ink-muted)', cursor: 'pointer', background: 'none', border: 'none' }}>Tenders 2026</button>
          <span style={{ color: 'var(--ink-subtle)' }}>/</span>
          {editing ? (
            <input
              autoFocus
              value={file}
              onChange={(e) => setFile(e.target.value)}
              onBlur={() => setEditing(false)}
              onKeyDown={(e) => { if (e.key === 'Enter') setEditing(false); }}
              style={{ background: 'var(--bg-elevated)', border: '1px solid var(--gold)', padding: '2px 6px', fontSize: 12, fontFamily: 'inherit', color: 'var(--ink)', outline: 'none', width: 260 }}
            />
          ) : (
            <button onClick={() => setEditing(true)} style={{ color: 'var(--ink)', fontWeight: 500, cursor: 'text', background: 'none', border: 'none', padding: 0 }}>{file}</button>
          )}
          <Badge tone="warn" style={{ marginLeft: 4 }}>Draft · v0.7</Badge>
        </Row>
      </Row>

      {/* Center: menu */}
      <Row gap={0} style={{ marginLeft: 20 }}>
        {['File','Edit','View','Object','Type','Effect','Window','Help'].map((m) => (
          <button key={m} style={{ padding: '4px 8px', fontSize: 12, color: 'var(--ink-3)', background: 'none', border: 'none', cursor: 'pointer' }}
            onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-panel-2)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
            {m}
          </button>
        ))}
      </Row>

      <div style={{ flex: 1 }}/>

      {/* Right: collaborators + actions */}
      <Row gap={6}>
        <Row gap={-4} style={{ marginRight: 6 }}>
          <Avatar name="Ananya Rao" tone="ink" size={22}/>
          <Avatar name="Sunil Iyer" tone="gold" size={22} style={{ marginLeft: -4, border: '2px solid var(--bg-panel)' }}/>
          <Avatar name="Meera Nair" tone="ink" size={22} style={{ marginLeft: -4, border: '2px solid var(--bg-panel)' }}/>
        </Row>
        <Btn variant="ghost" size="sm" icon={<I.users size={12}/>}>3</Btn>
        <Divider vertical style={{ height: 20 }}/>
        <Btn variant="ghost" size="sm" onClick={onOpenApproval} icon={<I.check size={12}/>}>Approval</Btn>
        <Btn variant="line" size="sm" onClick={onOpenExport} icon={<I.export size={12}/>}>Export</Btn>
        <Btn variant="solid" size="sm" icon={<I.share size={12}/>}>Share</Btn>
      </Row>
    </div>
  );
}

// ============ TOOLBAR (below top bar, contextual) ============
function EditorToolbar({ tool, selectedId, zoom, setZoom, showGrid, setShowGrid, showGuides, setShowGuides, showBleed, setShowBleed }) {
  return (
    <div style={{ height: 34, borderBottom: '1px solid var(--line)', background: 'var(--bg-panel)', display: 'flex', alignItems: 'center', padding: '0 12px', gap: 8 }}>
      <Row gap={4}>
        <Badge tone="neutral">{tool.toUpperCase()}</Badge>
        <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-muted)', letterSpacing: '0.04em' }}>
          {selectedId ? `Selected · ${selectedId}` : 'No selection'}
        </span>
      </Row>

      <Divider vertical style={{ height: 18, margin: '0 6px' }}/>

      <Row gap={2}>
        <IconBtn icon={<I.align_l size={13}/>} title="Align left"/>
        <IconBtn icon={<I.align_c size={13}/>} title="Align center"/>
        <IconBtn icon={<I.align_r size={13}/>} title="Align right"/>
        <Divider vertical style={{ height: 16, margin: '0 4px' }}/>
        <IconBtn icon={<I.copy size={13}/>} title="Duplicate"/>
        <IconBtn icon={<I.link size={13}/>} title="Link"/>
        <IconBtn icon={<I.trash size={13}/>} title="Delete"/>
      </Row>

      <div style={{ flex: 1 }}/>

      <Row gap={2}>
        <IconBtn icon={<I.grid size={13}/>} active={showGrid} onClick={() => setShowGrid(!showGrid)} title="Grid"/>
        <IconBtn icon={<I.align size={13}/>} active={showGuides} onClick={() => setShowGuides(!showGuides)} title="Guides"/>
        <Btn size="sm" variant={showBleed ? 'solid' : 'ghost'} onClick={() => setShowBleed(!showBleed)}>Bleed</Btn>
        <Divider vertical style={{ height: 16, margin: '0 4px' }}/>

        <IconBtn icon={<I.minus size={12}/>} size={22} onClick={() => setZoom(Math.max(0.25, zoom - 0.1))}/>
        <button onClick={() => setZoom(1)} className="mono" style={{ minWidth: 44, fontSize: 11, color: 'var(--ink-3)', background: 'none', border: 'none', cursor: 'pointer' }}>
          {Math.round(zoom * 100)}%
        </button>
        <IconBtn icon={<I.plus size={12}/>} size={22} onClick={() => setZoom(Math.min(4, zoom + 0.1))}/>
      </Row>
    </div>
  );
}

// ============ LEFT TOOL RAIL ============
function ToolRail({ tool, setTool }) {
  return (
    <div style={{
      width: 'var(--toolrail-w)',
      borderRight: '1px solid var(--line)',
      background: 'var(--bg-panel)',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      padding: '8px 0',
      gap: 2,
    }}>
      {TOOLS.map((t, i) => {
        const active = tool === t.key;
        return (
          <React.Fragment key={t.key}>
            {(i === 4 || i === 8) && <Divider style={{ width: '60%', margin: '4px 0' }}/>}
            <div style={{ position: 'relative' }} className="tool-item">
              <button
                onClick={() => setTool(t.key)}
                title={`${t.name} · ${t.shortcut}`}
                style={{
                  width: 36, height: 36,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  background: active ? 'var(--ink)' : 'transparent',
                  color: active ? 'var(--gold-2)' : 'var(--ink-2)',
                  border: '1px solid transparent',
                  cursor: 'pointer',
                  position: 'relative',
                }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-panel-2)'; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
              >
                {React.cloneElement(t.icon({}), { size: 16 })}
                {active && (
                  <span className="mono" style={{ position: 'absolute', bottom: 2, right: 3, fontSize: 8, color: 'var(--gold-2)', opacity: 0.7 }}>
                    {t.shortcut}
                  </span>
                )}
              </button>
            </div>
          </React.Fragment>
        );
      })}
      <div style={{ flex: 1 }}/>
      <Divider style={{ width: '60%', margin: '4px 0' }}/>
      <IconBtn icon={<I.swatch size={14}/>} size={36} title="Swatches"/>
      <IconBtn icon={<I.settings size={14}/>} size={36} title="Preferences"/>
    </div>
  );
}

// ============ RIGHT RAIL (panel tabs) ============
function RightRail({ rightTab, setRightTab }) {
  return (
    <div style={{
      width: 40,
      borderLeft: '1px solid var(--line)',
      background: 'var(--bg-panel)',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      padding: '8px 0',
      gap: 2,
    }}>
      {RIGHT_TABS.map((t) => {
        const active = rightTab === t.key;
        return (
          <button
            key={t.key}
            onClick={() => setRightTab(t.key)}
            title={t.name}
            style={{
              width: 28, height: 28,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              background: active ? 'var(--bg-panel-2)' : 'transparent',
              color: active ? 'var(--ink)' : 'var(--ink-muted)',
              borderLeft: active ? '2px solid var(--gold)' : '2px solid transparent',
              cursor: 'pointer',
              marginRight: -1,
            }}
            onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-panel-2)'; }}
            onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
          >
            {React.cloneElement(t.icon({}), { size: 14 })}
          </button>
        );
      })}
    </div>
  );
}

// ============ STATUS BAR ============
function StatusBar({ selectedId, tool, zoom }) {
  return (
    <div className="mono" style={{
      height: 'var(--statusbar-h)',
      borderTop: '1px solid var(--line)',
      background: 'var(--bg-panel)',
      display: 'flex',
      alignItems: 'center',
      padding: '0 12px',
      fontSize: 10.5,
      color: 'var(--ink-muted)',
      letterSpacing: '0.02em',
      gap: 16,
    }}>
      <Row gap={4}><span style={{ width: 6, height: 6, background: 'var(--status-ok)', display: 'inline-block' }}/> Autosaved · 14:32:17 IST</Row>
      <Divider vertical style={{ height: 12 }}/>
      <span>CMYK · Fogra 39 · 300 dpi</span>
      <Divider vertical style={{ height: 12 }}/>
      <span>A4 · 210 × 297 mm · Bleed 3 mm</span>
      <Divider vertical style={{ height: 12 }}/>
      <span>Fonts · 4 embedded</span>
      <Divider vertical style={{ height: 12 }}/>
      <span style={{ color: 'var(--status-warn)' }}>1 preflight warning</span>
      <div style={{ flex: 1 }}/>
      <span>Tool · {tool}</span>
      <Divider vertical style={{ height: 12 }}/>
      <span>Sel · {selectedId || '—'}</span>
      <Divider vertical style={{ height: 12 }}/>
      <span>Zoom · {Math.round(zoom * 100)}%</span>
      <Divider vertical style={{ height: 12 }}/>
      <span>x 142 y 316 mm</span>
    </div>
  );
}

Object.assign(window, { Editor });
