/* global React */
// ─────────────────────────────────────────────────────────────
// Mahana app catalog — uses real widget imagery the user supplied
// Each app has a full widget (border+label) + a squircle-only render
// for use in rails.
// ─────────────────────────────────────────────────────────────

// NOTE: using React.useState inline to avoid destructure collisions
// when this file shares scope with other components in the playground.

// Each app has TWO supplied renderings:
//   widget        — circular/blob outer border + glyph (iOS-springboard feel)
//   widgetSquare  — rounded-square outer tile + glyph + baked-in label
// AppIcon picks one based on `shape` prop ('circle' | 'square'); catalog order
// is load-bearing for layout elsewhere, don't shuffle.
const MAHANA_APPS = [
  { id: 'mail',       label: 'Mail',       widget: '../assets/apps/mail.png',       widgetSquare: '../assets/apps-square/mail.png',       desc: 'Inbox, threads, drafts' },
  { id: 'tasks',      label: 'Task Lists', widget: '../assets/apps/tasks.png',      widgetSquare: '../assets/apps-square/tasks.png',      desc: 'Projects & checklists' },
  { id: 'ideas',      label: 'Ideas',      widget: '../assets/apps/ideas.png',      widgetSquare: '../assets/apps-square/ideas.png',      desc: 'Capture & incubate' },
  { id: 'documents',  label: 'Documents',  widget: '../assets/apps/documents.png',  widgetSquare: '../assets/apps-square/documents.png',  desc: 'Docs & knowledge' },
  { id: 'designer',   label: 'Designer',   widget: '../assets/apps/designer.png',   widgetSquare: '../assets/apps-square/designer.png',   desc: 'Visual design workspace' },
  { id: 'panels',     label: 'Panels',     widget: '../assets/apps/panels.png',     widgetSquare: '../assets/apps-square/panels.png',     desc: 'Dashboards & canvases' },
  { id: 'accountant', label: 'Accountant', widget: '../assets/apps/accountant.png', widgetSquare: '../assets/apps-square/accountant.png', desc: 'Books & invoices' },
  { id: 'vault',      label: 'Vault',      widget: '../assets/apps/vault.png',      widgetSquare: '../assets/apps-square/vault.png',      desc: 'Identity & secrets' },
  { id: 'website',    label: 'Website',    widget: '../assets/apps/website.png',    widgetSquare: '../assets/apps-square/website.png',    desc: 'Web & research' },
  { id: 'apps',       label: 'Apps',       widget: '../assets/apps/apps.png',       widgetSquare: '../assets/apps-square/apps.png',       desc: 'App library' },
  { id: 'aiapps',     label: 'AI Apps',    widget: '../assets/apps/aiapps.png',     widgetSquare: '../assets/apps-square/aiapps.png',     desc: 'AI shortcuts' },
];

// Lookup
const APPS_BY_ID = Object.fromEntries(MAHANA_APPS.map(a => [a.id, a]));

// Each widget PNG has the outer rainbow border + label baked in.
// Each icon PNG is a clean circular glyph (transparent bg, icon centered).
// Render full-bleed — the PNG already has the circular container + padding.
function AppIcon({ app, size = 44, active, onClick, showLabel = false, shape = 'circle', style = {} }) {
  const data = typeof app === 'string' ? APPS_BY_ID[app] : app;
  if (!data) return null;
  const src = (shape === 'square' && data.widgetSquare) ? data.widgetSquare : data.widget;
  return (
    <div
      onClick={onClick}
      title={data.label}
      style={{
        position: 'relative',
        width: size, height: size,
        cursor: onClick ? 'pointer' : 'default',
        flexShrink: 0,
        transform: active ? 'scale(1.12)' : 'scale(1)',
        transition: 'transform 180ms cubic-bezier(0.2,0.9,0.2,1), filter 180ms',
        filter: active ? 'drop-shadow(0 4px 14px rgba(255, 80, 180, 0.45))' : 'none',
        ...style,
      }}
      onMouseEnter={e => !active && (e.currentTarget.style.transform = 'scale(1.08)')}
      onMouseLeave={e => !active && (e.currentTarget.style.transform = 'scale(1)')}
    >
      <img
        src={src}
        alt={data.label}
        draggable={false}
        style={{
          width: '100%', height: '100%',
          objectFit: 'contain',
          userSelect: 'none',
          display: 'block',
        }}
      />
      {active && (
        <div style={{
          position: 'absolute', inset: -2,
          borderRadius: '50%',
          boxShadow: '0 0 0 2px rgba(255, 80, 180, 0.55)',
          pointerEvents: 'none',
        }} />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AppRail — vertical rail of apps. Primary (size=44) or slim (size=22)
// ─────────────────────────────────────────────────────────────
function AppRail({ apps = MAHANA_APPS, active, onOpen, size = 44, slim = false }) {
  const tileSize = slim ? 22 : size;
  return (
    <div style={{
      display: 'flex', flexDirection: 'column',
      gap: slim ? 6 : 10,
      padding: slim ? '6px 4px' : '12px 10px',
      alignItems: 'center',
    }}>
      {apps.map(app => (
        <AppIcon
          key={app.id}
          app={app}
          size={tileSize}
          active={active === app.id}
          onClick={() => onOpen?.(app.id)}
        />
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// UnifierPanel — what opens when you click an app in the rail.
// Floats above the chat, sheet-style, with app-appropriate content.
// ─────────────────────────────────────────────────────────────
function UnifierPanel({ appId, onClose }) {
  const app = APPS_BY_ID[appId];
  if (!app) return null;

  return (
    <aside style={{
      width: 360, flexShrink: 0,
      background: 'rgba(255,255,255,0.88)',
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
      borderLeft: '1px solid rgba(0,0,0,0.08)',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
      animation: 'unifier-in 280ms cubic-bezier(0.2,0.9,0.2,1)',
    }}>
      <style>{`
        @keyframes unifier-in {
          from { opacity: 0; transform: translateX(12px); }
          to   { opacity: 1; transform: translateX(0); }
        }
      `}</style>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '16px 18px',
        borderBottom: '1px solid rgba(0,0,0,0.06)',
      }}>
        <AppIcon app={app} size={36} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: window.MM_FONT, fontSize: 10.5, fontWeight: 600,
            letterSpacing: '0.08em', textTransform: 'uppercase',
            color: 'rgba(0,0,0,0.45)', marginBottom: 2,
          }}>Focus · {app.label}</div>
          <div style={{ fontFamily: window.MM_SERIF, fontWeight: 500, fontSize: 16,
                        color: '#1A1A1A', letterSpacing: -0.2 }}>
            Answering with {app.label.toLowerCase()} context
          </div>
        </div>
        <button onClick={onClose} style={{
          padding: '6px 10px', borderRadius: 7,
          background: 'rgba(0,0,0,0.04)', border: '1px solid rgba(0,0,0,0.08)',
          fontFamily: window.MM_FONT, fontSize: 12, color: 'rgba(0,0,0,0.6)',
          cursor: 'pointer',
        }}>✕</button>
      </div>

      {/* Body — app-specific preview */}
      <div style={{ flex: 1, overflow: 'auto', padding: '18px 20px' }}>
        <UnifierBody appId={appId} />
      </div>
    </aside>
  );
}

// ─────────────────────────────────────────────────────────────
// UnifierBody — per-app mock content
// ─────────────────────────────────────────────────────────────
function UnifierBody({ appId }) {
  if (appId === 'mail') return <MailUnifier />;
  if (appId === 'tasks') return <TasksUnifier />;
  if (appId === 'ideas') return <IdeasUnifier />;
  if (appId === 'documents') return <DocsUnifier />;
  if (appId === 'accountant') return <AccountantUnifier />;
  if (appId === 'panels') return <PanelsUnifier />;
  if (appId === 'designer') return <DesignerUnifier />;
  if (appId === 'vault') return <VaultUnifier />;
  if (appId === 'website') return <WebsiteUnifier />;
  return <GenericUnifier appId={appId} />;
}

const cellStyle = {
  display: 'flex', alignItems: 'center', gap: 12,
  padding: '10px 12px', borderRadius: 10,
  fontFamily: window.MM_FONT, fontSize: 13,
};

function MailUnifier() {
  const threads = [
    { from: 'Elena Park', subj: 'Re: term sheet for Q3 round', preview: 'We can go 18 at 6, but…', unread: true, time: '9:41', ai: '3 summarized by Mastermind' },
    { from: 'Stripe',     subj: 'Payout complete · $47,209',    preview: 'Transferred to Mercury ••9821', unread: true, time: '9:12' },
    { from: 'Han Yu',     subj: 'Customer interview notes',     preview: 'Top 3 quotes tagged w/ risk', unread: false, time: 'Yest' },
    { from: 'calendly',   subj: 'Meeting in 15 minutes',        preview: 'Design review w/ Jordan', unread: false, time: 'Yest' },
  ];
  return (
    <div>
      <div style={{ fontFamily: window.MM_FONT, fontSize: 12, color: 'rgba(0,0,0,0.5)', marginBottom: 10 }}>
        <b style={{ color: 'rgba(255, 80, 180, 0.9)' }}>Mastermind</b> · I scanned 47 threads. Here are the 4 that need you:
      </div>
      {threads.map((t, i) => (
        <div key={i} style={{
          ...cellStyle,
          borderBottom: i < threads.length - 1 ? '1px solid rgba(0,0,0,0.05)' : 'none',
          background: t.unread ? 'rgba(255, 120, 200, 0.04)' : 'transparent',
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: '50%',
            background: `hsl(${i * 80} 70% 65%)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 11.5, fontWeight: 600, flexShrink: 0,
          }}>{t.from.split(' ').map(s => s[0]).join('').slice(0, 2)}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', gap: 6, alignItems: 'baseline' }}>
              <span style={{ fontWeight: t.unread ? 600 : 500, color: 'rgba(0,0,0,0.85)' }}>{t.from}</span>
              <span style={{ flex: 1 }} />
              <span style={{ fontSize: 11, color: 'rgba(0,0,0,0.4)' }}>{t.time}</span>
            </div>
            <div style={{ color: 'rgba(0,0,0,0.75)', fontSize: 12.5, fontWeight: 500 }}>{t.subj}</div>
            <div style={{ color: 'rgba(0,0,0,0.5)', fontSize: 12, textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden' }}>
              {t.preview}
            </div>
            {t.ai && <div style={{ fontSize: 11, color: 'rgba(255, 80, 180, 0.85)', marginTop: 2 }}>✦ {t.ai}</div>}
          </div>
        </div>
      ))}
    </div>
  );
}

function TasksUnifier() {
  const cols = [
    { name: 'Today',    items: [
      { t: 'Review Elena\'s term sheet', done: false, tag: 'Fintech R&D' },
      { t: 'Reply to Stripe payout confirm', done: true },
      { t: 'Ship ledger schema draft', done: false, tag: 'Mahana' },
    ]},
    { name: 'This week', items: [
      { t: 'Interview 3 more fintech users', done: false },
      { t: 'Wire Conductor mode to Claude Haiku', done: false, tag: 'Mastermind' },
      { t: 'Offsite dinner menu', done: false, tag: 'SF' },
    ]},
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {cols.map(col => (
        <div key={col.name}>
          <div style={{ fontFamily: window.MM_FONT, fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6, color: 'rgba(0,0,0,0.45)', marginBottom: 8 }}>
            {col.name}
          </div>
          {col.items.map((i, n) => (
            <div key={n} style={{
              ...cellStyle,
              padding: '8px 8px',
              opacity: i.done ? 0.5 : 1,
            }}>
              <div style={{
                width: 16, height: 16, borderRadius: 4,
                border: `1.5px solid ${i.done ? 'rgba(255, 80, 180, 0.6)' : 'rgba(0,0,0,0.2)'}`,
                background: i.done ? 'rgba(255, 80, 180, 0.8)' : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontSize: 10, flexShrink: 0,
              }}>{i.done ? '✓' : ''}</div>
              <span style={{ flex: 1, textDecoration: i.done ? 'line-through' : 'none',
                             color: 'rgba(0,0,0,0.82)' }}>{i.t}</span>
              {i.tag && (
                <span style={{ fontSize: 10.5, fontWeight: 500, padding: '2px 7px',
                               borderRadius: 4, background: 'rgba(255, 80, 180, 0.1)',
                               color: 'rgba(180, 40, 120, 0.9)' }}>{i.tag}</span>
              )}
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

function IdeasUnifier() {
  const ideas = [
    { t: 'What if every app had its own Mastermind?',
      b: 'Chorus narrows as the app narrows. Mail-Mastermind would only see your inbox. Tasks-Mastermind only sees your projects.',
      tags: ['product', 'mastermind'] },
    { t: 'Rename "agents" to "minds"',
      b: 'It\'s a Mahana word already. Mastermind, mind-reader, keep-in-mind. Agents is Zapier energy.',
      tags: ['copy'] },
    { t: 'Confidence as a first-class metric',
      b: 'Don\'t just show one verdict — show each mind\'s % next to its mark, always visible.',
      tags: ['design'] },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {ideas.map((i, n) => (
        <div key={n} style={{
          padding: 14, borderRadius: 12,
          background: 'rgba(255, 240, 248, 0.7)',
          border: '1px solid rgba(255, 180, 220, 0.4)',
          fontFamily: window.MM_FONT,
        }}>
          <div style={{ fontWeight: 600, fontSize: 13.5, color: 'rgba(0,0,0,0.85)', marginBottom: 4 }}>{i.t}</div>
          <div style={{ fontSize: 12.5, color: 'rgba(0,0,0,0.6)', lineHeight: 1.45 }}>{i.b}</div>
          <div style={{ display: 'flex', gap: 5, marginTop: 8 }}>
            {i.tags.map(tg => (
              <span key={tg} style={{ fontSize: 10.5, padding: '2px 7px', borderRadius: 4,
                                       background: 'rgba(0,0,0,0.05)', color: 'rgba(0,0,0,0.55)' }}>#{tg}</span>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function DocsUnifier() {
  const docs = [
    { t: 'Ledger Schema v3', s: 'Mahana · 12 min read', pct: 74 },
    { t: 'Fintech Launch Plan', s: 'Fintech R&D · 8 min', pct: 52 },
    { t: 'Design System: Mastermind', s: 'Design · 22 min', pct: 100 },
    { t: 'Q3 OKRs', s: 'Mahana · 4 min', pct: 18 },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
      {docs.map((d, i) => (
        <div key={i} style={{
          padding: 14, borderRadius: 10,
          border: '1px solid rgba(0,0,0,0.08)',
          fontFamily: window.MM_FONT,
        }}>
          <div style={{ fontWeight: 600, fontSize: 13, color: 'rgba(0,0,0,0.85)', marginBottom: 2 }}>{d.t}</div>
          <div style={{ fontSize: 11.5, color: 'rgba(0,0,0,0.5)', marginBottom: 10 }}>{d.s}</div>
          <div style={{ height: 3, background: 'rgba(0,0,0,0.06)', borderRadius: 2 }}>
            <div style={{ width: `${d.pct}%`, height: '100%', background: 'rgba(255, 80, 180, 0.7)', borderRadius: 2 }} />
          </div>
        </div>
      ))}
    </div>
  );
}

function AccountantUnifier() {
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 14 }}>
        {[
          { k: 'Runway', v: '14 mo', sub: '+2mo vs Feb' },
          { k: 'MRR', v: '$47.2K', sub: '+18% MoM' },
          { k: 'Burn', v: '$62K', sub: '−8% MoM' },
        ].map(s => (
          <div key={s.k} style={{ padding: 14, borderRadius: 10, background: 'rgba(0,0,0,0.03)',
                                   fontFamily: window.MM_FONT }}>
            <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.5)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.6 }}>{s.k}</div>
            <div style={{ fontSize: 22, fontWeight: 600, fontFamily: window.MM_SERIF, color: 'rgba(0,0,0,0.9)', marginTop: 2 }}>{s.v}</div>
            <div style={{ fontSize: 11, color: 'rgba(255, 80, 180, 0.85)' }}>{s.sub}</div>
          </div>
        ))}
      </div>
      <div style={{ fontFamily: window.MM_FONT, fontSize: 12.5, color: 'rgba(0,0,0,0.7)', lineHeight: 1.5 }}>
        <b style={{ color: 'rgba(255, 80, 180, 0.9)' }}>Mastermind · </b>
        Three anomalies this month: the AWS bill dropped $1.4K (right-sizing from last week), Stripe's Europe disbursement is 2 days late,
        and your Clay subscription renewed at a higher tier. All three flagged in Mail.
      </div>
    </div>
  );
}

function PanelsUnifier() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
      {['Revenue', 'Churn', 'Sessions', 'Activations', 'DAU', 'NPS'].map(p => (
        <div key={p} style={{ height: 100, borderRadius: 10, padding: 12,
                               background: `linear-gradient(140deg, rgba(255,${120 + Math.random()*80},${180},0.12), rgba(180,${80 + Math.random()*80},${255},0.08))`,
                               fontFamily: window.MM_FONT }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'rgba(0,0,0,0.55)', textTransform: 'uppercase', letterSpacing: 0.5 }}>{p}</div>
          <svg width="100%" height="50" style={{ marginTop: 6 }}>
            <polyline
              fill="none"
              stroke="rgba(255, 80, 180, 0.7)"
              strokeWidth="2"
              points={Array.from({length: 10}, (_,i) => `${i * 12},${20 + Math.sin(i + p.length) * 10 + Math.random() * 8}`).join(' ')}
            />
          </svg>
        </div>
      ))}
    </div>
  );
}

function DesignerUnifier() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
      {Array.from({length: 8}).map((_, i) => (
        <div key={i} style={{
          aspectRatio: '3/4', borderRadius: 10,
          background: `conic-gradient(from ${i * 40}deg, hsl(${i * 45} 80% 70%), hsl(${i * 45 + 120} 80% 75%), hsl(${i * 45} 80% 70%))`,
          filter: `blur(${i % 2 === 0 ? '0' : '1px'})`,
          boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
        }} />
      ))}
    </div>
  );
}

function VaultUnifier() {
  const items = [
    { k: 'Apple ID',        type: 'Login',    last: '2d ago' },
    { k: 'Anthropic API',   type: 'API Key',  last: '5m ago' },
    { k: 'Mercury Bank',    type: 'Login',    last: '1h ago' },
    { k: 'Delaware LLC EIN',type: 'Document', last: '2 mo ago' },
  ];
  return (
    <div>
      {items.map((i, n) => (
        <div key={n} style={{ ...cellStyle, borderBottom: '1px solid rgba(0,0,0,0.05)' }}>
          <div style={{ width: 28, height: 28, borderRadius: 7,
                         background: 'linear-gradient(140deg, #ff8fc8, #ab6cff)',
                         display: 'flex', alignItems: 'center', justifyContent: 'center',
                         color: '#fff', fontSize: 13 }}>🔒</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 500, color: 'rgba(0,0,0,0.85)' }}>{i.k}</div>
            <div style={{ fontSize: 11.5, color: 'rgba(0,0,0,0.5)' }}>{i.type} · used {i.last}</div>
          </div>
          <span style={{ fontSize: 11, color: 'rgba(0,0,0,0.4)' }}>••••••••</span>
        </div>
      ))}
    </div>
  );
}

function WebsiteUnifier() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {[
        { t: 'Stripe · Double-entry accounting guide', url: 'stripe.com/docs/accounting', snip: 'Why financial systems should never allow partial writes; transactions and the invariant balance=credit−debit…' },
        { t: 'Hacker News discussion: Rust vs Go for fintech', url: 'news.ycombinator.com/item?id=…', snip: 'ThePrimeagen\'s take: "Go for ship, Rust for correctness." 340 comments.' },
        { t: 'Matt Rickard · Why we picked Postgres', url: 'matt-rickard.com/postgres-fintech', snip: 'After 3 years on CockroachDB we moved back. Here\'s the full accounting of why.' },
      ].map((r, i) => (
        <div key={i} style={{ padding: 12, borderRadius: 10, border: '1px solid rgba(0,0,0,0.07)',
                                fontFamily: window.MM_FONT }}>
          <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.5)' }}>{r.url}</div>
          <div style={{ fontWeight: 600, fontSize: 13, color: 'rgba(255, 80, 180, 0.9)', marginTop: 2 }}>{r.t}</div>
          <div style={{ fontSize: 12.5, color: 'rgba(0,0,0,0.68)', lineHeight: 1.45, marginTop: 4 }}>{r.snip}</div>
        </div>
      ))}
    </div>
  );
}

function GenericUnifier({ appId }) {
  const app = APPS_BY_ID[appId];
  return (
    <div style={{ textAlign: 'center', padding: '40px 0', fontFamily: window.MM_FONT,
                   color: 'rgba(0,0,0,0.5)' }}>
      <AppIcon app={app} size={72} style={{ margin: '0 auto 16px' }} />
      <div style={{ fontSize: 14, color: 'rgba(0,0,0,0.8)', fontWeight: 500 }}>{app.label}</div>
      <div style={{ fontSize: 12, marginTop: 4 }}>{app.desc}</div>
    </div>
  );
}

// SquircleIcon = icon-only (no label). AppIcon already renders a clean squircle glyph.
const SquircleIcon = AppIcon;

Object.assign(window, { MAHANA_APPS, APPS_BY_ID, AppIcon, SquircleIcon, AppRail, UnifierPanel });
