// Workspace — Edge states canvas + Component library shown via DesignCanvas

function EdgeStatesCanvas({ identity }) {
  return (
    <DesignCanvas>
      <DCSection id="edge" title="Edge states & loading" subtitle="Empty, loading, error, conflict, no-results — todos los estados que el equipo va a encontrar.">
        <DCArtboard id="empty-vault" label="Empty · Vault" width={760} height={520}>
          <EmptyArtboard kind="vault" />
        </DCArtboard>
        <DCArtboard id="empty-folder" label="Empty · /inbox vacía" width={760} height={520}>
          <EmptyArtboard kind="folder" />
        </DCArtboard>
        <DCArtboard id="empty-tracker" label="Empty · Tracker" width={760} height={520}>
          <EmptyArtboard kind="tracker" />
        </DCArtboard>
        <DCArtboard id="empty-search" label="Empty · sin resultados" width={760} height={520}>
          <EmptyArtboard kind="search" />
        </DCArtboard>
        <DCArtboard id="loading" label="Loading · skeletons" width={760} height={520}>
          <LoadingArtboard />
        </DCArtboard>
        <DCArtboard id="error" label="Error · banner rojo" width={760} height={520}>
          <ErrorArtboard />
        </DCArtboard>
        <DCArtboard id="conflict" label="Conflict · editor" width={760} height={520}>
          <ConflictArtboard />
        </DCArtboard>
        <DCArtboard id="modal" label="Modal · confirmación" width={760} height={520}>
          <ModalArtboard />
        </DCArtboard>
      </DCSection>

      <DCSection id="components" title="Component library" subtitle="Botones, badges, avatares, inputs, toasts, skeletons.">
        <DCArtboard id="buttons" label="Botones" width={520} height={420}>
          <CompArtboard><ComponentButtons /></CompArtboard>
        </DCArtboard>
        <DCArtboard id="inputs" label="Inputs" width={520} height={420}>
          <CompArtboard><ComponentInputs /></CompArtboard>
        </DCArtboard>
        <DCArtboard id="badges" label="Badges & chips" width={520} height={420}>
          <CompArtboard><ComponentBadges /></CompArtboard>
        </DCArtboard>
        <DCArtboard id="avatars" label="Avatares (4 actores)" width={520} height={420}>
          <CompArtboard><ComponentAvatars /></CompArtboard>
        </DCArtboard>
        <DCArtboard id="toasts" label="Toasts" width={520} height={420}>
          <CompArtboard><ComponentToasts /></CompArtboard>
        </DCArtboard>
        <DCArtboard id="cards" label="Cards & estados" width={520} height={420}>
          <CompArtboard><ComponentCards /></CompArtboard>
        </DCArtboard>
      </DCSection>

      <DCSection id="onboarding" title="Onboarding flow" subtitle="3 pasos · primera apertura.">
        <DCArtboard id="ob-1" label="1 · Identidad" width={900} height={620}><FrameWrap><Onboarding step={1} onChange={() => {}} /></FrameWrap></DCArtboard>
        <DCArtboard id="ob-2" label="2 · Vault" width={900} height={620}><FrameWrap><Onboarding step={2} onChange={() => {}} /></FrameWrap></DCArtboard>
        <DCArtboard id="ob-3" label="3 · Fases" width={900} height={620}><FrameWrap><Onboarding step={3} onChange={() => {}} /></FrameWrap></DCArtboard>
      </DCSection>

      <DCSection id="palette" title="Command palette · ⌘K" subtitle="Acceso rápido a docs, tareas y comandos.">
        <DCArtboard id="cmdk" label="⌘K abierto" width={900} height={620}>
          <FrameWrap><div style={{ position: 'absolute', inset: 0, background: 'var(--bg-0)' }}/><CommandPalette onClose={() => {}} /></FrameWrap>
        </DCArtboard>
      </DCSection>
    </DesignCanvas>
  );
}

function FrameWrap({ children }) {
  return <div style={{ position: 'relative', width: '100%', height: '100%', background: 'var(--bg-0)', overflow: 'hidden' }}>{children}</div>;
}

function CompArtboard({ children }) {
  return <div style={{ width: '100%', height: '100%', background: 'var(--bg-0)', padding: 24, overflow: 'auto' }}>{children}</div>;
}

function EmptyArtboard({ kind }) {
  const cfg = {
    vault:   { icon: 'library',     title: 'Tu Vault está vacío',           body: 'Crea tu primer documento o importa archivos existentes para empezar.', cta: 'Nuevo documento', sec: 'Importar archivos' },
    folder:  { icon: 'folder-open', title: 'Esta carpeta está vacía',       body: 'Crea un documento o súbelo desde Claude Code para que aparezca aquí.', cta: 'Nuevo documento' },
    tracker: { icon: 'kanban',      title: 'Tu Tracker está vacío',         body: 'Crea tu primera tarea o importa todas las fases del proyecto de una vez.', cta: 'Crear primera tarea', sec: 'Importar fases del proyecto' },
    search:  { icon: 'search-x',    title: 'Sin resultados',                body: 'No encontramos nada para "compilator". Prueba con otros términos o revisa la ortografía.', cta: 'Limpiar búsqueda' },
  }[kind];
  return (
    <div style={{ height: '100%', padding: 24, background: 'var(--bg-0)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginBottom: 12 }} className="mono">/ {kind === 'folder' ? 'inbox' : kind}</div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <EmptyState iconName={cfg.icon} title={cfg.title} body={cfg.body} cta={cfg.cta} ctaIcon="plus" secondaryCta={cfg.sec} />
      </div>
    </div>
  );
}

function LoadingArtboard() {
  return (
    <div style={{ padding: 24, background: 'var(--bg-0)', height: '100%' }}>
      <Skeleton w={220} h={28} style={{ marginBottom: 8 }} />
      <Skeleton w={140} h={12} style={{ marginBottom: 24 }} />
      <Skeleton w="100%" h={42} style={{ marginBottom: 28, borderRadius: 8 }} />
      <Skeleton w={180} h={16} style={{ marginBottom: 14 }} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
        {[0,1,2,3,4,5].map(i => (
          <div key={i} style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: 16 }}>
            <Skeleton w={70} h={10} style={{ marginBottom: 10 }} />
            <Skeleton w="80%" h={14} style={{ marginBottom: 10 }} />
            <Skeleton w="100%" h={10} style={{ marginBottom: 4 }} />
            <Skeleton w="60%" h={10} style={{ marginBottom: 12 }} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Skeleton w={18} h={18} style={{ borderRadius: 9 }} />
              <Skeleton w={80} h={10} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ErrorArtboard() {
  return (
    <div style={{ padding: 24, background: 'var(--bg-0)', height: '100%', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{
        background: 'rgba(239,68,68,.08)', border: '1px solid rgba(239,68,68,.30)',
        borderRadius: 8, padding: '12px 14px',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <Icon name="alert-circle" size={16} color="var(--danger)" />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-0)' }}>No pudimos cargar el documento</div>
          <div style={{ fontSize: 12, color: 'var(--text-1)', marginTop: 2 }}>El servidor respondió <span className="mono">503 Service Unavailable</span>. Intenta de nuevo en unos segundos.</div>
        </div>
        <Button variant="secondary" size="sm" icon="refresh-cw">Reintentar</Button>
      </div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-3)', fontSize: 12, fontStyle: 'italic' }}>
        El editor permanece vacío hasta que recuperemos el contenido.
      </div>
    </div>
  );
}

function ConflictArtboard() {
  return (
    <div style={{ height: '100%', background: 'var(--bg-0)' }}>
      <div style={{
        background: 'rgba(245,158,11,.08)', borderBottom: '1px solid rgba(245,158,11,.30)',
        padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, fontSize: 13,
      }}>
        <Icon name="alert-triangle" size={15} color="var(--warn)" />
        <span style={{ color: 'var(--text-0)' }}>
          Este documento fue modificado por <span style={{ color: 'var(--code)', fontWeight: 500 }}>Claude Code</span> hace 2 minutos.
        </span>
        <div style={{ flex: 1 }} />
        <Button variant="ghost" size="sm">Ver cambios</Button>
        <Button variant="secondary" size="sm">Recargar</Button>
        <Button variant="primary" size="sm">Sobreescribir</Button>
      </div>
      <div style={{ padding: 24, display: 'flex', gap: 12, fontFamily: 'var(--font-mono)', fontSize: 12, lineHeight: 1.7, color: 'var(--text-1)' }}>
        <div style={{ width: 28, color: 'var(--text-3)', textAlign: 'right' }}>{'12\n13\n14\n15\n16'.split('\n').map((n,i) => <div key={i}>{n}</div>)}</div>
        <pre style={{ margin: 0, color: 'var(--text-0)' }}>
{`fn tokenize_number(s: &Str) -> Token {
  // <-- conflicto entre tu cambio y el de Claude Code
  let base = detect_base(s);
  return Token::Numeric { value, span };
}`}
        </pre>
      </div>
    </div>
  );
}

function ModalArtboard() {
  return (
    <div style={{ position: 'relative', height: '100%', background: 'var(--bg-0)' }}>
      <div style={{ padding: 24, opacity: 0.4 }}>
        <Skeleton w={200} h={20} style={{ marginBottom: 14 }} />
        <Skeleton w="100%" h={300} style={{ borderRadius: 12 }} />
      </div>
      <Modal
        title="Borrar este documento"
        body="Vas a borrar /specs/parte1.md. Esto removerá la última versión del Vault. Las versiones anteriores siguen disponibles en el historial por 30 días."
        danger confirmLabel="Borrar documento" cancelLabel="Cancelar"
        onConfirm={() => {}} onCancel={() => {}} />
    </div>
  );
}

// ── Component library artboards ─────────────────────────────────────
function CompRow({ label, children }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ fontSize: 10.5, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600, marginBottom: 8 }}>{label}</div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>{children}</div>
    </div>
  );
}

function ComponentButtons() {
  return (
    <div>
      <CompRow label="Primary"><Button variant="primary">Guardar</Button><Button variant="primary" icon="plus">Nuevo</Button><Button variant="primary" disabled>Disabled</Button></CompRow>
      <CompRow label="Secondary"><Button variant="secondary">Cancelar</Button><Button variant="secondary" icon="filter">Filtrar</Button></CompRow>
      <CompRow label="Ghost"><Button variant="ghost" icon="history">Historial</Button><Button variant="ghost" icon="settings">Ajustes</Button></CompRow>
      <CompRow label="Danger"><Button variant="danger" icon="trash-2">Borrar</Button><Button variant="dangerSolid" icon="trash-2">Borrar permanente</Button></CompRow>
      <CompRow label="Sizes"><Button variant="primary" size="sm">Small</Button><Button variant="primary" size="md">Medium</Button><Button variant="primary" size="lg">Large</Button></CompRow>
    </div>
  );
}

function ComponentInputs() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <CompRow label="Default"><div style={{ width: 280 }}><TextInput value="" onChange={() => {}} placeholder="Buscar…" icon="search" /></div></CompRow>
      <CompRow label="Con kbd hint"><div style={{ width: 280 }}><TextInput value="" onChange={() => {}} placeholder="Comando…" icon="search" kbd="⌘K" /></div></CompRow>
      <CompRow label="Con valor"><div style={{ width: 280 }}><TextInput value="lexer numeric" onChange={() => {}} icon="search" /></div></CompRow>
      <CompRow label="Textarea">
        <textarea placeholder="Comentar…" rows={3} style={{
          width: 320, background: 'var(--bg-1)', border: '1px solid var(--border)',
          borderRadius: 8, padding: 10, color: 'var(--text-0)', fontFamily: 'inherit', fontSize: 13, resize: 'vertical', outline: 'none',
        }} />
      </CompRow>
      <CompRow label="Select"><Select label="Filtrar por autor" value="Todos" /><Select label="Ordenar" value="Último editado" /></CompRow>
      <CompRow label="Checkbox"><Checkbox checked={false} onChange={() => {}} /><Checkbox checked={true} onChange={() => {}} /><Checkbox mixed onChange={() => {}} /></CompRow>
    </div>
  );
}

function ComponentBadges() {
  return (
    <div>
      <CompRow label="Estado de tarea">
        {Object.entries(STATUS_META).map(([k, m]) => (
          <Badge key={k} color={m.color} bg={m.bg} dot>{m.label}</Badge>
        ))}
      </CompRow>
      <CompRow label="Prioridad"><PriorityChip p="P0" /><PriorityChip p="P1" /><PriorityChip p="P2" /><PriorityChip p="P3" /></CompRow>
      <CompRow label="Fase"><Tag mono>II-6</Tag><Tag mono>II-7</Tag><Tag mono>II-8</Tag><Tag>lexer</Tag><Tag>tokens</Tag></CompRow>
      <CompRow label="Otros"><Badge color="var(--success)" bg="rgba(16,185,129,.10)" dot>guardado</Badge><Badge color="var(--warn)" bg="rgba(245,158,11,.10)" dot>conflicto</Badge><Badge color="var(--code)" bg="rgba(168,85,247,.10)" dot>code agent</Badge></CompRow>
    </div>
  );
}

function ComponentAvatars() {
  return (
    <div>
      <CompRow label="Avatar individual · 4 actores">
        {ACTOR_LIST.map(id => (
          <div key={id} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <Avatar actor={id} size={36} />
            <span style={{ fontSize: 10.5, color: 'var(--text-2)' }}>{ACTORS[id].name}</span>
          </div>
        ))}
      </CompRow>
      <CompRow label="Tamaños"><Avatar actor="founder" size={16} /><Avatar actor="founder" size={20} /><Avatar actor="founder" size={28} /><Avatar actor="founder" size={40} /><Avatar actor="founder" size={56} ring /></CompRow>
      <CompRow label="Stack"><AvatarStack actors={['founder', 'tlead', 'code', 'claude']} /></CompRow>
    </div>
  );
}

function ComponentToasts() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <Toast kind="success" title="Documento guardado" body="parte1.md · 248 palabras" />
      <Toast kind="error" title="No se pudo guardar" body="Conexión perdida. Reintentando en 5s…" />
      <Toast kind="info" title="Claude Code editó" body="Modificó /specs/parte2.md hace 12s" />
      <Toast kind="warn" title="Tarea pasada de fecha" body="T-046 venció ayer · Genaro" />
    </div>
  );
}

function ComponentCards() {
  const t = TASKS[8];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
      <div><div style={{ fontSize: 10.5, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600, marginBottom: 6 }}>Default</div><TaskCard task={t} onClick={() => {}} /></div>
      <div><div style={{ fontSize: 10.5, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600, marginBottom: 6 }}>Hover</div><TaskCard task={t} hover onClick={() => {}} /></div>
      <div><div style={{ fontSize: 10.5, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600, marginBottom: 6 }}>Bloqueada</div><TaskCard task={TASKS.find(x => x.status === 'blocked')} onClick={() => {}} /></div>
      <div><div style={{ fontSize: 10.5, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600, marginBottom: 6 }}>Compacta</div><TaskCardCompact task={t} onClick={() => {}} /></div>
    </div>
  );
}

Object.assign(window, { EdgeStatesCanvas });
