/**
 * app/share/space/[token]/page.js — Public read-only space viewer.
 *
 * No session required. Verifies the space share token, handles the optional
 * email-OTP gate, and renders a gallery of the space's CURRENT artifacts
 * (resolved live, so artifacts added or moved into the space after the link was
 * created appear automatically). Chromeless (see app/components/app-chrome.jsx).
 */

import {
  verifySpaceShareLink,
  recordSpaceShareLinkAccess,
  listSpaceArtifactsForShare,
} from '@/lib/space-acl.js';
import SpaceOtpGate from './space-otp-gate.jsx';
import PublicSpaceCanvas from './public-space-canvas.jsx';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

// This route lives under the app root layout, which already renders
// <html>/<body>. AppChrome only strips the sidebar for /share/* (chromeless) —
// it does NOT give us a fresh document root. Rendering our own <html> here
// nests <html> inside <div> and breaks hydration. So the layout is a plain
// in-page wrapper; the document title comes from generateMetadata.

const SHARE_STYLES = `
  .space-wrap { max-width: 900px; margin: 0 auto; padding: 2.5rem 1.5rem; min-height: 100vh; background: #fafafa; color: #1a1a1a; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
  .space-wrap--canvas { max-width: none; width: 100%; padding: 0; background: #0f1013; }
  .space-header { margin-bottom: 2rem; padding-bottom: 1.25rem; border-bottom: 1px solid #e5e7eb; }
  .space-eyebrow { font-size: 0.6875rem; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; color: #C2452A; }
  .space-title { font-size: 1.6rem; font-weight: 600; line-height: 1.25; margin-top: 0.35rem; }
  .space-meta { margin-top: 0.5rem; font-size: 0.8125rem; color: #666; }
  .space-artifact { margin-bottom: 2.25rem; }
  .space-artifact-head { font-size: 0.95rem; font-weight: 600; margin-bottom: 0.6rem; display: flex; align-items: center; gap: 0.5rem; }
  .space-artifact-kind { font-size: 0.625rem; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; color: #6b7280; background: #eef0f2; border-radius: 999px; padding: 2px 8px; }
  .space-empty { color: #6b7280; font-size: 0.95rem; padding: 2rem 0; }
  .share-markdown h1, .share-markdown h2, .share-markdown h3 { margin: 1.25rem 0 0.6rem; font-weight: 600; }
  .share-markdown p { margin-bottom: 0.85rem; }
  .share-markdown li { margin-left: 1.5rem; margin-bottom: 0.25rem; }
  .share-markdown code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 3px; font-size: 0.875em; }
  .share-markdown strong { font-weight: 600; }
`;

export async function generateMetadata({ params }) {
  const { token } = await params;
  const result = await verifySpaceShareLink(token).catch(() => null);
  const name = result?.ok ? result.space?.name : null;
  return {
    title: name ? `${name} — madarX` : 'Shared space — madarX',
    robots: { index: false, follow: false },
  };
}

function SpaceShareLayout({ spaceName, count, canvasMode = false, children }) {
  return (
    <div className={canvasMode ? 'space-wrap space-wrap--canvas' : 'space-wrap'}>
      <style>{SHARE_STYLES}</style>
      {!canvasMode && (
        <div className="space-header">
          <div className="space-eyebrow">Shared space</div>
          <h1 className="space-title">{spaceName || 'Shared space'}</h1>
          {typeof count === 'number' ? (
            <p className="space-meta">{count} artifact{count === 1 ? '' : 's'}</p>
          ) : null}
        </div>
      )}
      {children}
    </div>
  );
}

const ERROR_MESSAGES = {
  expired: { title: 'Link Expired', body: 'This shared space link has expired and is no longer accessible.' },
  revoked: { title: 'Link Revoked', body: 'This shared space link has been revoked by its owner.' },
  view_cap_reached: { title: 'View Limit Reached', body: 'This shared space link has reached its maximum number of views.' },
  not_found: { title: 'Not Found', body: 'This shared space link does not exist or has been removed.' },
};

export default async function SpaceSharePage({ params }) {
  const { token } = await params;

  const result = await verifySpaceShareLink(token);

  if (!result.ok) {
    const msg = ERROR_MESSAGES[result.reason] || ERROR_MESSAGES.not_found;
    return (
      <SpaceShareLayout>
        <div style={{ textAlign: 'center', padding: '3rem 1rem' }}>
          <h1 style={{ fontSize: '1.5rem', fontWeight: 600, marginBottom: '0.75rem' }}>{msg.title}</h1>
          <p style={{ color: '#666', maxWidth: '38ch', margin: '0 auto' }}>{msg.body}</p>
        </div>
      </SpaceShareLayout>
    );
  }

  const { link, space } = result;

  // OTP gate — verification + artifact fetch happen client-side after the code
  // is confirmed (the gate calls GET /api/share/space/[token]).
  if (link.require_email_otp === 1) {
    return (
      <SpaceShareLayout spaceName={space.name}>
        <SpaceOtpGate token={token} spaceName={space.name} />
      </SpaceShareLayout>
    );
  }

  // No OTP — record the access (increments view count + auto-revokes at cap)
  // and render the live artifact gallery.
  recordSpaceShareLinkAccess(link.id, null, null);
  const artifacts = listSpaceArtifactsForShare(space.id);

  // node:sqlite rows have a null prototype and cannot cross the
  // Server→Client boundary. Re-shape into plain objects, and pass only the
  // fields the client canvas needs — never the link's HMAC/owner/org columns.
  const safeSpace = { id: space.id, name: space.name };
  const safeLink = { expires_at: link.expires_at ?? null };
  const safeArtifacts = artifacts.map((a) => ({
    id: a.id,
    title: a.title ?? null,
    kind: a.kind ?? null,
    content: a.content ?? null,
    source_md: a.source_md ?? null,
    public_layout: a.public_layout ?? null,
    layout: a.layout ?? null,
    position: a.position ?? null,
  }));

  return (
    <SpaceShareLayout spaceName={space.name} count={safeArtifacts.length} canvasMode={safeArtifacts.length > 0}>
      {safeArtifacts.length === 0 ? (
        <p className="space-empty">This space has no artifacts yet. New artifacts will appear here automatically.</p>
      ) : (
        <PublicSpaceCanvas token={token} space={safeSpace} artifacts={safeArtifacts} link={safeLink} />
      )}
    </SpaceShareLayout>
  );
}
