// Dashboard — the workspace home screen. Formal, information-dense.

const MODULES = [
  { key: 'draw',     name: 'ChitraKar Draw',       tag: 'DRAW',   icon: I.vector, desc: 'Vector graphics · Illustration', color: 'var(--ink)' },
  { key: 'photo',    name: 'ChitraKar Photo',      tag: 'PHOTO',  icon: I.photo,  desc: 'Raster editing · Retouch',        color: 'var(--ink)' },
  { key: 'publish',  name: 'ChitraKar Publisher',  tag: 'PUB',    icon: I.publish,desc: 'Layout · Print · Prepress',       color: 'var(--ink)' },
  { key: 'ui',       name: 'ChitraKar UI',         tag: 'UI',     icon: I.ui,     desc: 'Interface · Prototype',           color: 'var(--ink)' },
  { key: 'ai',       name: 'ChitraKar AI Studio',  tag: 'AI',     icon: I.ai,     desc: 'Generative · Assist',             color: 'var(--gold)' },
  { key: 'brand',    name: 'ChitraKar Brand Hub',  tag: 'BRAND',  icon: I.brand,  desc: 'Kits · Assets · Governance',      color: 'var(--ink)' },
  { key: 'collab',   name: 'ChitraKar Collaborate',tag: 'COLLAB', icon: I.collab, desc: 'Review · Approval workflow',      color: 'var(--ink)' },
  { key: 'print',    name: 'ChitraKar Print',      tag: 'PRINT',  icon: I.print,  desc: 'Preflight · Production',          color: 'var(--ink)' },
  { key: 'cloud',    name: 'ChitraKar Cloud',      tag: 'CLOUD',  icon: I.cloud,  desc: 'Storage · Sync · Backup',         color: 'var(--ink)' },
  { key: 'admin',    name: 'ChitraKar Admin',      tag: 'ADMIN',  icon: I.admin,  desc: 'Users · Security · Audit',        color: 'var(--ink)' },
];

const RECENT = [
  { id: 'DGN-2864', title: 'Tender Notice — Rural Development',   client: 'Ministry of Rural Development', updated: '14 min ago',   status: 'draft',    module: 'PUB',   pages: '4 pages',  size: 'A4' },
  { id: 'DGN-2851', title: 'Digital India — Awareness Poster',    client: 'MeitY',                          updated: '2 hr ago',     status: 'review',   module: 'DRAW',  pages: '1 artboard', size: 'A3 landscape' },
  { id: 'DGN-2847', title: 'Kisan Credit Card — Bilingual',       client: 'NABARD',                         updated: 'Yesterday',    status: 'approved', module: 'PUB',   pages: '2 pages',  size: '85×54 mm' },
  { id: 'DGN-2842', title: 'Annual Report — Cover · Section II',  client: 'Bureau of Indian Standards',     updated: '2 days ago',   status: 'review',   module: 'PUB',   pages: '48 pages', size: 'A4' },
  { id: 'DGN-2838', title: 'Aarogya Setu — Kiosk Interface',      client: 'NIC · GoI',                      updated: '3 days ago',   status: 'draft',    module: 'UI',    pages: '12 screens', size: '1920×1080' },
  { id: 'DGN-2831', title: 'Swachh Bharat — Certificate Batch',   client: 'MoHUA',                          updated: '5 days ago',   status: 'published',module: 'PUB',   pages: '1,247 gen.', size: 'A4' },
  { id: 'DGN-2825', title: 'Republic Day Greeting — Draft',       client: 'Internal',                       updated: '1 wk ago',     status: 'archived', module: 'DRAW',  pages: '1 artboard', size: '1080×1080' },
];

const TEMPLATE_CATS = [
  { name: 'Government Notice',   count: 148, hero: true },
  { name: 'Tender Cover',        count: 42 },
  { name: 'Certificate',         count: 96 },
  { name: 'Report · Annual',     count: 31 },
  { name: 'ID Card',             count: 58 },
  { name: 'Business Card',       count: 74 },
  { name: 'Poster · Awareness',  count: 112 },
  { name: 'Letterhead',          count: 39 },
];

const STATUS_TONE = {
  draft:     'neutral',
  review:    'warn',
  approved:  'ok',
  published: 'info',
  archived:  'neutral',
};

function Dashboard({ onOpenModule, onOpenProject }) {
  return (
    <div style={{ height: '100%', overflow: 'auto', background: 'var(--bg)' }}>
      {/* Top brand bar */}
      <DashboardTopBar />

      <div style={{ maxWidth: 1400, margin: '0 auto', padding: '24px 32px 48px' }}>
        {/* Ministry / org header */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'end', gap: 16, paddingBottom: 20, borderBottom: '1px solid var(--line)' }}>
          <div>
            <Row gap={12} style={{ marginBottom: 8 }}>
              <Label>Workspace · Government of India</Label>
              <Badge tone="ok"><span style={{ width: 4, height: 4, background: 'var(--status-ok)', display: 'inline-block' }}/> On-Premises</Badge>
              <Badge tone="neutral">v3.2.14 · LTS</Badge>
            </Row>
            <h1 className="serif" style={{ margin: 0, fontSize: 36, fontWeight: 500, letterSpacing: '-0.01em', color: 'var(--ink)' }}>
              Ministry of Rural Development
              <span className="dev" style={{ display: 'block', fontSize: 22, marginTop: 2, color: 'var(--ink-3)', fontWeight: 400 }}>
                ग्रामीण विकास मंत्रालय
              </span>
            </h1>
            <div className="mono" style={{ marginTop: 10, fontSize: 11.5, color: 'var(--ink-muted)', letterSpacing: '0.02em' }}>
              Design Cell · Krishi Bhavan, New Delhi · <span style={{ color: 'var(--ink-3)' }}>Registered Users 214</span> · <span style={{ color: 'var(--ink-3)' }}>Active Now 27</span>
            </div>
          </div>
          <Row gap={8}>
            <Btn variant="line" icon={<I.search size={13}/>}>Search designs<Kbd>⌘K</Kbd></Btn>
            <Btn variant="line" icon={<I.import size={13}/>}>Import</Btn>
            <Btn variant="solid" icon={<I.plus size={13}/>} onClick={() => onOpenModule('draw')}>New Design</Btn>
          </Row>
        </div>

        {/* Section: Modules */}
        <SectionHeader label="Modules" caption="10 of 10 licensed" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 1, background: 'var(--line)', border: '1px solid var(--line)' }}>
          {MODULES.map((m) => (
            <ModuleTile key={m.key} mod={m} onClick={() => onOpenModule(m.key)} />
          ))}
        </div>

        {/* Two-col: Recent designs + Sidebar */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 32, marginTop: 40 }}>
          <div>
            <SectionHeader label="Recent Designs" caption="Last 7 days" right={
              <Row gap={4}>
                <Btn size="sm" variant="ghost" icon={<I.filter size={11}/>}>Filter</Btn>
                <Btn size="sm" variant="ghost" icon={<I.sort size={11}/>}>Sort</Btn>
              </Row>
            }/>
            <RecentTable rows={RECENT} onOpen={onOpenProject} />
          </div>

          <div>
            <SectionHeader label="Templates" caption="Certified library" />
            <TemplateList items={TEMPLATE_CATS} />

            <SectionHeader label="Approvals · Pending You" caption="3 items" style={{ marginTop: 32 }} />
            <ApprovalStack />

            <SectionHeader label="System" caption="On-premises · IN-Delhi-01" style={{ marginTop: 32 }} />
            <SystemStack />
          </div>
        </div>
      </div>
    </div>
  );
}

function DashboardTopBar() {
  return (
    <div style={{ height: 44, borderBottom: '1px solid var(--line)', background: 'var(--bg-panel)', padding: '0 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <Row gap={16}>
        <Row gap={8}>
          <Logo size={22}/>
          <div style={{ fontWeight: 600, fontSize: 13.5, letterSpacing: '-0.01em' }}>ChitraKar</div>
          <Badge tone="neutral" style={{ marginLeft: 4 }}>Enterprise</Badge>
        </Row>
        <Divider vertical style={{ height: 20 }}/>
        <Row gap={2}>
          <Btn variant="ghost" size="sm" active>Workspace</Btn>
          <Btn variant="ghost" size="sm">Assets</Btn>
          <Btn variant="ghost" size="sm">Reviews</Btn>
          <Btn variant="ghost" size="sm">Reports</Btn>
          <Btn variant="ghost" size="sm">Admin</Btn>
        </Row>
      </Row>
      <Row gap={8}>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-muted)', letterSpacing: '0.06em' }}>SSO · KERBEROS · dev@mord.gov.in</div>
        <Divider vertical style={{ height: 20 }}/>
        <IconBtn icon={<I.bell size={14}/>} size={26} />
        <IconBtn icon={<I.settings size={14}/>} size={26} />
        <Avatar name="Ananya Rao" tone="ink"/>
      </Row>
    </div>
  );
}

function Logo({ size = 22 }) {
  return (
    <div style={{
      width: size, height: size,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--ink)',
      color: 'var(--gold-2)',
      fontFamily: "'Fraunces', serif",
      fontWeight: 600,
      fontSize: size * 0.62,
      letterSpacing: '-0.03em',
    }}>
      च
    </div>
  );
}

function SectionHeader({ label, caption, right, style }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', margin: '36px 0 12px', ...style }}>
      <Row gap={12} align="baseline">
        <Label style={{ fontSize: 11 }}>{label}</Label>
        {caption && <span className="mono" style={{ fontSize: 11, color: 'var(--ink-subtle)' }}>· {caption}</span>}
      </Row>
      {right}
    </div>
  );
}

function ModuleTile({ mod, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: hover ? 'var(--bg-elevated)' : 'var(--bg-panel)',
        padding: '18px 16px 16px',
        textAlign: 'left',
        cursor: 'pointer',
        transition: 'background 120ms',
        display: 'flex',
        flexDirection: 'column',
        gap: 10,
        minHeight: 132,
        position: 'relative',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div style={{ color: mod.color }}>{React.cloneElement(mod.icon({}), { size: 22 })}</div>
        <span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-subtle)', letterSpacing: '0.1em' }}>{mod.tag}</span>
      </div>
      <div>
        <div className="serif" style={{ fontSize: 15, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.005em' }}>
          {mod.name.replace('ChitraKar ', '')}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-muted)', marginTop: 3 }}>{mod.desc}</div>
      </div>
      {hover && (
        <div style={{ position: 'absolute', bottom: 12, right: 14, color: 'var(--ink-muted)' }}>
          <I.arrow size={12}/>
        </div>
      )}
    </button>
  );
}

function RecentTable({ rows, onOpen }) {
  return (
    <div style={{ border: '1px solid var(--line)', background: 'var(--bg-panel)' }}>
      <div className="mono" style={{
        display: 'grid',
        gridTemplateColumns: '82px 1fr 200px 100px 110px 32px',
        fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase',
        color: 'var(--ink-subtle)',
        padding: '8px 12px',
        borderBottom: '1px solid var(--line)',
      }}>
        <div>ID</div>
        <div>Title</div>
        <div>Client / Dept.</div>
        <div>Updated</div>
        <div>Status</div>
        <div></div>
      </div>
      {rows.map((r, i) => (
        <div
          key={r.id}
          onClick={() => onOpen(r)}
          style={{
            display: 'grid',
            gridTemplateColumns: '82px 1fr 200px 100px 110px 32px',
            fontSize: 12.5,
            padding: '10px 12px',
            borderBottom: i < rows.length - 1 ? '1px solid var(--line)' : 'none',
            cursor: 'pointer',
            alignItems: 'center',
            transition: 'background 80ms',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-elevated)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
        >
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-muted)' }}>{r.id}</div>
          <div>
            <div style={{ color: 'var(--ink)', fontWeight: 500 }}>{r.title}</div>
            <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-subtle)', marginTop: 2 }}>
              [{r.module}] · {r.pages} · {r.size}
            </div>
          </div>
          <div style={{ color: 'var(--ink-3)', fontSize: 12 }}>{r.client}</div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-muted)' }}>{r.updated}</div>
          <div><Badge tone={STATUS_TONE[r.status]}>{r.status}</Badge></div>
          <div style={{ color: 'var(--ink-subtle)', textAlign: 'right' }}><I.more size={14}/></div>
        </div>
      ))}
    </div>
  );
}

function TemplateList({ items }) {
  return (
    <div style={{ border: '1px solid var(--line)', background: 'var(--bg-panel)' }}>
      {items.map((t, i) => (
        <div
          key={t.name}
          style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '8px 12px',
            borderBottom: i < items.length - 1 ? '1px solid var(--line)' : 'none',
            cursor: 'pointer',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-elevated)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
        >
          <div style={{ fontSize: 12.5, color: 'var(--ink)' }}>{t.name}</div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-subtle)' }}>{String(t.count).padStart(3, '0')}</div>
        </div>
      ))}
      <div style={{ padding: '10px 12px', borderTop: '1px solid var(--line)', background: 'var(--bg-panel-2)' }}>
        <Btn size="sm" variant="ghost" iconRight={<I.arrow size={11}/>} style={{ width: '100%', justifyContent: 'space-between' }}>Browse all 748</Btn>
      </div>
    </div>
  );
}

function ApprovalStack() {
  const items = [
    { title: 'Tender Notice — MoRD',   from: 'S. Iyer',    role: 'Reviewer',       stage: '2/4', ago: '17 min' },
    { title: 'BSNL Rebrand — Assets',  from: 'R. Krishnan', role: 'Under Secretary', stage: '3/4', ago: '2 hr' },
    { title: 'Kisan Awareness — Set',  from: 'M. Nair',    role: 'Designer',       stage: '1/4', ago: '4 hr' },
  ];
  return (
    <div style={{ border: '1px solid var(--line)', background: 'var(--bg-panel)' }}>
      {items.map((x, i) => (
        <div key={x.title} style={{
          padding: '10px 12px',
          borderBottom: i < items.length - 1 ? '1px solid var(--line)' : 'none',
        }}>
          <div style={{ fontSize: 12.5, color: 'var(--ink)', fontWeight: 500 }}>{x.title}</div>
          <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-muted)', marginTop: 3, display: 'flex', justifyContent: 'space-between' }}>
            <span>from {x.from} · {x.role}</span>
            <span>Stage {x.stage} · {x.ago}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function SystemStack() {
  const items = [
    { label: 'Storage · Cloud',   value: '2.4 TB / 8 TB',   pct: 30 },
    { label: 'Storage · Local',   value: '412 GB / 2 TB',   pct: 20 },
    { label: 'AI Inference · Q3', value: '18,244 / 50,000', pct: 36 },
    { label: 'Active Licenses',   value: '214 / 300',       pct: 71 },
  ];
  return (
    <div style={{ border: '1px solid var(--line)', background: 'var(--bg-panel)' }}>
      {items.map((x, i) => (
        <div key={x.label} style={{
          padding: '10px 12px',
          borderBottom: i < items.length - 1 ? '1px solid var(--line)' : 'none',
        }}>
          <Row justify="space-between" style={{ marginBottom: 6 }}>
            <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{x.label}</span>
            <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-muted)' }}>{x.value}</span>
          </Row>
          <div style={{ height: 3, background: 'var(--bg-panel-2)', borderRadius: 0 }}>
            <div style={{ width: `${x.pct}%`, height: '100%', background: x.pct > 70 ? 'var(--status-warn)' : 'var(--ink)' }}/>
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Dashboard, Logo });
