Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

32.7 KB
Raw Blame
import React, { useEffect, useMemo, useState } from 'react';
import {
  Bug,
  FilePlus,
  FolderOpen,
  Globe,
  Plus,
  Search,
  Star,
  X,
} from 'lucide-react';
import { uiStoreActions, useUiStore } from '../stores';
import { isImeComposing, useI18n } from '../i18n';
import type { CanvasColorMode, NewCanvasOptions } from '../types/editor';
import type { ChromeStyle, DensityPreset } from '../types/appearance';
import { ThemePreset } from '../types/settings';
import {
  RecentDocument,
  formatFileSize,
  loadRecentDocuments,
  permanentlyDeleteDocument,
  removeRecentDocument,
  toggleStarDocument,
} from '../utils/recentDocumentsManager';
import { DeleteDocumentModal } from './DeleteDocumentModal';
import { COMMUNITY_LINKS } from './SocialIcons';
import { GITHUB_ISSUES_URL, openExternalUrl } from '../utils/externalLinks';

export interface WelcomeQuickPreset {
  id: string;
  label: string;
  width: number;
  height: number;
  dpi: number;
  ratioLabel: string;
  colorMode: CanvasColorMode;
  defaultFrequency?: number;
  tag: string;
}

export const WELCOME_QUICK_PRESETS: readonly WelcomeQuickPreset[] = [
  {
    id: 'illustration-4k',
    label: 'Illustration 4K',
    width: 3840,
    height: 2160,
    dpi: 300,
    ratioLabel: '16:9',
    colorMode: 'color',
    tag: '16:9',
  },
  {
    id: 'manga-b4-600',
    label: 'Manga B4',
    width: 6071,
    height: 8598,
    dpi: 600,
    ratioLabel: 'B4',
    colorMode: 'monochrome',
    defaultFrequency: 60,
    tag: '600 DPI',
  },
  {
    id: 'webtoon-strip',
    label: 'Webtoon',
    width: 800,
    height: 1280,
    dpi: 150,
    ratioLabel: '5:8',
    colorMode: 'color',
    tag: '5:8',
  },
  {
    id: 'square-study',
    label: 'Square Study',
    width: 2048,
    height: 2048,
    dpi: 300,
    ratioLabel: '1:1',
    colorMode: 'color',
    tag: '1:1',
  },
] as const;

interface WelcomeScreenProps {
  userName: string;
  onNewDocument: () => void;
  onCreateQuickCanvas?: (options: NewCanvasOptions) => void;
  onOpenFile: () => void;
  onSelectRecentDocument?: (doc: RecentDocument) => void;
  showToast: (msg: string) => void;
  themePreset?: ThemePreset;
}

const InkStudioMark: React.FC<{ className?: string }> = ({ className = 'w-5 h-5' }) => (
  <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
    <rect
      x="2.25"
      y="2.25"
      width="19.5"
      height="19.5"
      rx="3"
      stroke="currentColor"
      strokeWidth="1.4"
      opacity="0.45"
    />
    <path
      d="M12 5.25L16.5 13.1L12 18.75L7.5 13.1L12 5.25Z"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinejoin="round"
    />
    <path d="M12 5.25V12.2" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" />
    <circle cx="12" cy="13.2" r="1.25" fill="currentColor" />
  </svg>
);

function formatExtensionTag(doc: RecentDocument): string {
  const raw =
    doc.fileType ||
    (doc.title.includes('.') ? doc.title.slice(doc.title.lastIndexOf('.')) : '');
  const clean = raw.replace(/^\./, '').trim().toUpperCase();
  return clean || 'INK';
}

const DENSITY_LAYOUT: Record<
  DensityPreset,
  {
    containerPad: string;
    sectionGap: string;
    cardPad: string;
    gridGap: string;
  }
> = {
  compact: {
    containerPad: 'px-5 py-6',
    sectionGap: 'space-y-6',
    cardPad: 'p-2',
    gridGap: 'gap-2.5',
  },
  balanced: {
    containerPad: 'px-6 py-7',
    sectionGap: 'space-y-7',
    cardPad: 'p-2.5',
    gridGap: 'gap-3',
  },
  comfortable: {
    containerPad: 'px-8 py-9',
    sectionGap: 'space-y-8',
    cardPad: 'p-3',
    gridGap: 'gap-3.5',
  },
};

export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
  userName,
  onNewDocument,
  onCreateQuickCanvas,
  onOpenFile,
  onSelectRecentDocument,
  showToast,
}) => {
  const { lang, t, td } = useI18n();
  const appearance = useUiStore((s) => s.appSettings.appearance);
  const density: DensityPreset = appearance.density ?? 'balanced';
  const chromeStyle: ChromeStyle = appearance.chromeStyle ?? 'hairline';
  const layout = DENSITY_LAYOUT[density] ?? DENSITY_LAYOUT.balanced;

  const [documents, setDocuments] = useState<RecentDocument[]>([]);
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [deleteTargetDoc, setDeleteTargetDoc] = useState<RecentDocument | null>(null);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState<boolean>(false);

  useEffect(() => {
    let isMounted = true;
    loadRecentDocuments().then((docs) => {
      if (isMounted) setDocuments(docs);
    });
    return () => {
      isMounted = false;
    };
  }, []);

  const handleQuickStartPreset = (preset: WelcomeQuickPreset) => {
    if (!onCreateQuickCanvas) {
      onNewDocument();
      return;
    }
    onCreateQuickCanvas({
      name: `${td(preset.label)}*`,
      width: preset.width,
      height: preset.height,
      dpi: preset.dpi,
      aspectRatioPreset: preset.id,
      aspectRatioX: preset.width,
      aspectRatioY: preset.height,
      lockAspectRatio: false,
      backgroundColor: '#ffffff',
      colorMode: preset.colorMode,
      defaultFrequency: preset.defaultFrequency ?? 60,
    });
  };

  const handleToggleStar = async (doc: RecentDocument, e: React.MouseEvent) => {
    e.stopPropagation();
    const newStarred = await toggleStarDocument(doc.id);
    setDocuments((prev) =>
      prev.map((d) => (d.id === doc.id ? { ...d, isStarred: newStarred } : d))
    );
    showToast(
      newStarred
        ? t('Pinned "{title}"', { title: doc.title })
        : t('Unpinned "{title}"', { title: doc.title })
    );
  };

  const handleOpenDelete = (doc: RecentDocument, e: React.MouseEvent) => {
    e.stopPropagation();
    setDeleteTargetDoc(doc);
    setIsDeleteModalOpen(true);
  };

  const handleHideFromApp = async (doc: RecentDocument) => {
    setIsDeleteModalOpen(false);
    await removeRecentDocument(doc.id);
    setDocuments((prev) => prev.filter((d) => d.id !== doc.id));
    setDeleteTargetDoc(null);
    showToast(t('Removed "{title}"', { title: doc.title }));
  };

  const handlePermanentDelete = async (doc: RecentDocument) => {
    setIsDeleteModalOpen(false);
    const result = await permanentlyDeleteDocument(doc);
    setDocuments((prev) => prev.filter((d) => d.id !== doc.id));
    setDeleteTargetDoc(null);
    showToast(
      result.success ? t('Deleted "{title}"', { title: doc.title }) : t('Removed from list')
    );
  };

  const cleanQuery = searchQuery.trim().toLowerCase();
  const filtered = useMemo(
    () =>
      documents.filter((doc) => {
        if (!cleanQuery) return true;
        return (
          doc.title.toLowerCase().includes(cleanQuery) ||
          doc.path.toLowerCase().includes(cleanQuery)
        );
      }),
    [cleanQuery, documents]
  );

  const starredDocs = useMemo(() => filtered.filter((d) => d.isStarred), [filtered]);
  const trimmedName = userName?.trim() || '';

  const surfaceCardChrome =
    chromeStyle === 'flat'
      ? 'bg-ui-panel border border-ui-subtle hover:border-ui-strong hover:bg-ui-control/55'
      : chromeStyle === 'islands'
        ? 'bg-ui-panel border border-ui-default hover:border-ui-strong hover:bg-ui-control/55 shadow-sm'
        : 'bg-ui-panel border border-ui-subtle hover:border-ui-strong hover:bg-ui-control/55';

  const headerBorderChrome =
    chromeStyle === 'flat' ? 'border-b border-ui-subtle' : 'border-b border-ui-default';

  const primaryBtnChrome =
    chromeStyle === 'islands'
      ? 'rounded-ui-md shadow-xs'
      : 'rounded-ui-sm';

  const secondaryBtnChrome =
    chromeStyle === 'flat'
      ? 'rounded-ui-sm bg-ui-control/85 hover:bg-ui-control-hover border border-ui-subtle hover:border-ui-default'
      : chromeStyle === 'islands'
        ? 'rounded-ui-md bg-ui-panel hover:bg-ui-control-hover border border-ui-default hover:border-ui-strong shadow-xs'
        : 'rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default hover:border-ui-strong';

  const socialGroupChrome =
    chromeStyle === 'flat'
      ? 'inline-flex items-center gap-0.5 pl-2 border-l border-ui-subtle shrink-0'
      : chromeStyle === 'islands'
        ? 'inline-flex items-center gap-1 shrink-0'
        : 'inline-flex items-center rounded-ui-sm bg-ui-panel border border-ui-default divide-x divide-ui-subtle overflow-hidden shrink-0';

  const socialItemChrome =
    chromeStyle === 'flat'
      ? 'ui-icon-stroke h-[var(--ui-control-height)] w-[var(--ui-control-height)] flex items-center justify-center rounded-ui-sm bg-transparent hover:bg-ui-control-hover text-ui-icon-muted hover:text-ui-primary transition-colors cursor-pointer focus:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ui-focus'
      : chromeStyle === 'islands'
        ? 'ui-icon-stroke h-[var(--ui-control-height)] w-[var(--ui-control-height)] flex items-center justify-center rounded-ui-md bg-ui-panel hover:bg-ui-control-hover border border-ui-default hover:border-ui-strong shadow-xs text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer focus:outline-none focus-visible:border-ui-focus'
        : 'ui-icon-stroke h-[calc(var(--ui-control-height)-2px)] w-[calc(var(--ui-control-height)-2px)] flex items-center justify-center bg-transparent hover:bg-ui-control-hover text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer focus:outline-none focus-visible:bg-ui-control-hover focus-visible:text-ui-primary focus-visible:shadow-[inset_0_0_0_1px_var(--ui-border-focus)]';

  const socialIconSize = density === 'comfortable' ? 'w-4 h-4' : 'w-3.5 h-3.5';

  const footerChrome =
    chromeStyle === 'flat'
      ? 'border-t border-ui-subtle pt-3'
      : chromeStyle === 'islands'
        ? 'rounded-ui-md bg-ui-panel/85 border border-ui-default shadow-xs px-3 py-2'
        : 'border-t border-ui-default pt-3';

  const footerLinkChrome =
    chromeStyle === 'flat'
      ? 'ui-icon-stroke inline-flex items-center gap-1.5 px-1.5 py-1 rounded-ui-xs text-[10.5px] text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover/70 transition-colors cursor-pointer focus:outline-none focus-visible:ring-1 focus-visible:ring-ui-focus'
      : chromeStyle === 'islands'
        ? 'ui-icon-stroke inline-flex items-center gap-1.5 px-2 py-1 rounded-ui-sm border border-transparent hover:border-ui-default text-[10.5px] text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer focus:outline-none focus-visible:border-ui-focus'
        : 'ui-icon-stroke inline-flex items-center gap-1.5 px-2 py-1 rounded-ui-xs border border-transparent hover:border-ui-subtle text-[10.5px] text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer focus:outline-none focus-visible:border-ui-focus';

  return (
    <div
      data-testid="welcome-atelier-hub"
      data-density={density}
      data-chrome-style={chromeStyle}
      className="flex-1 flex flex-col h-full bg-ui-void ui-drafting-grid text-ui-primary overflow-y-auto select-none"
    >
      {/* Crisp Atelier Top Bar */}
      <header className={`sticky top-0 z-20 bg-ui-header/95 ${headerBorderChrome} backdrop-blur-[4px]`}>
        <div className="max-w-5xl w-full mx-auto px-6 py-3 flex flex-wrap items-center justify-between gap-3">
          {/* Typographic Mark & Greeting */}
          <div className="flex items-center gap-2.5 min-w-0">
            <div className="w-8 h-8 rounded-ui-sm bg-ui-panel border border-ui-default flex items-center justify-center text-ui-accent shrink-0">
              <InkStudioMark className="w-5 h-5" />
            </div>
            <div className="min-w-0">
              <div className="flex items-center gap-2">
                <span className="text-[10px] font-ui-mono uppercase tracking-[0.14em] text-ui-muted leading-none">
                  Ink Studio
                </span>
              </div>
              <h1 className="text-[14px] font-medium tracking-[-0.01em] text-ui-primary truncate mt-0.5 leading-tight">
                {trimmedName ? t('Welcome back, {name}', { name: trimmedName }) : t('Studio Workspace')}
              </h1>
            </div>
          </div>

          {/* Integrated Search + Primary Actions + Community Links */}
          <div className="flex flex-wrap items-center gap-2 flex-1 sm:flex-initial justify-end min-w-[240px]">
            <div className="relative flex-1 sm:w-52 md:w-60 min-w-[140px]">
              <Search className="w-3.5 h-3.5 text-ui-icon-muted absolute left-2.5 top-1/2 -translate-y-1/2 pointer-events-none" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={(e) => {
                  if (isImeComposing(e)) return;
                  if (e.key === 'Escape' && searchQuery) {
                    setSearchQuery('');
                  }
                }}
                placeholder={t('Search projects...')}
                aria-label={t('Search recent documents')}
                className="w-full h-[var(--ui-control-height)] pl-8 pr-7 text-[11.5px] bg-ui-input border border-ui-subtle hover:border-ui-default focus:border-ui-focus rounded-ui-sm text-ui-primary placeholder:text-ui-muted transition-colors"
              />
              {searchQuery && (
                <button
                  type="button"
                  onClick={() => setSearchQuery('')}
                  aria-label={t('Clear search')}
                  className="absolute right-2 top-1/2 -translate-y-1/2 text-ui-muted hover:text-ui-primary cursor-pointer"
                >
                  <X className="w-3 h-3" />
                </button>
              )}
            </div>

            <button
              type="button"
              data-testid="welcome-new-canvas-btn"
              onClick={onNewDocument}
              className={`ui-icon-stroke h-[var(--ui-control-height)] flex items-center gap-1.5 px-3 bg-ui-accent text-ui-accent-contrast text-[11.5px] font-medium transition-opacity hover:opacity-90 cursor-pointer shrink-0 ${primaryBtnChrome}`}
            >
              <FilePlus className="w-3.5 h-3.5" />
              <span>{t('New Canvas')}</span>
            </button>

            <button
              type="button"
              data-testid="welcome-open-file-btn"
              onClick={onOpenFile}
              className={`ui-icon-stroke h-[var(--ui-control-height)] flex items-center gap-1.5 px-3 text-[11.5px] font-medium text-ui-primary transition-colors cursor-pointer shrink-0 ${secondaryBtnChrome}`}
            >
              <FolderOpen className="w-3.5 h-3.5 text-ui-icon-muted" />
              <span>{t('Open File')}</span>
            </button>

            <button
              type="button"
              data-testid="welcome-language-toggle"
              onClick={() => {
                const next = lang === 'ja' ? 'en' : 'ja';
                uiStoreActions.setLanguage(next);
                showToast(
                  next === 'ja' ? '表示言語を日本語に変更しました' : 'Language changed to English'
                );
              }}
              title={lang === 'ja' ? 'Switch to English' : '日本語に切り替え'}
              aria-label={lang === 'ja' ? 'Switch language to English' : '表示言語を日本語に切り替え'}
              className={`ui-icon-stroke h-[var(--ui-control-height)] flex items-center gap-1 px-2 text-[11px] font-medium text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer shrink-0 ${secondaryBtnChrome}`}
            >
              <Globe className="w-3.5 h-3.5 text-ui-icon-muted" />
              <span>{lang === 'ja' ? 'EN' : '日本語'}</span>
            </button>

            <nav
              aria-label={t('Community and project links')}
              data-testid="welcome-social-links"
              data-chrome-style={chromeStyle}
              className={socialGroupChrome}
            >
              {COMMUNITY_LINKS.map((link) => (
                <a
                  key={link.id}
                  href={link.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  data-testid={`welcome-social-${link.id}`}
                  onClick={(e) => {
                    e.preventDefault();
                    void openExternalUrl(link.url);
                  }}
                  title={td(link.title)}
                  aria-label={td(link.title)}
                  className={socialItemChrome}
                >
                  {link.renderIcon(socialIconSize)}
                </a>
              ))}
            </nav>
          </div>
        </div>
      </header>

      {/* Main Atelier Content */}
      <main className={`max-w-5xl w-full mx-auto flex-1 flex flex-col ${layout.containerPad} ${layout.sectionGap}`}>
        {/* 1. Quick-Start Canvas Strip */}
        <section aria-label={t('Quick-Start Canvases')} className="space-y-2.5">
          <div className="flex items-center justify-between border-b border-ui-subtle pb-1.5">
            <h2 className="text-[10.5px] font-medium uppercase tracking-[0.08em] text-ui-muted">
              {t('Quick-Start Sheets')}
            </h2>
            <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
              {t('1-click canvas')}
            </span>
          </div>

          <div
            data-testid="welcome-quick-start-strip"
            className={`grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 ${layout.gridGap}`}
          >
            {WELCOME_QUICK_PRESETS.map((preset) => {
              const isLandscape = preset.width > preset.height;
              const isSquare = preset.width === preset.height;
              return (
                <button
                  key={preset.id}
                  type="button"
                  data-testid={`welcome-preset-${preset.id}`}
                  onClick={() => handleQuickStartPreset(preset)}
                  className={`group flex flex-col text-left rounded-ui-md transition-colors cursor-pointer ${layout.cardPad} ${surfaceCardChrome}`}
                >
                  {/* Proportional Sheet Schematic */}
                  <div className="w-full h-14 rounded-ui-xs bg-ui-input/80 border border-ui-subtle flex items-center justify-center p-2 mb-2 relative overflow-hidden">
                    <div
                      style={{
                        aspectRatio: `${preset.width} / ${preset.height}`,
                        width: isLandscape ? '66%' : isSquare ? '36px' : 'auto',
                        height: isLandscape ? 'auto' : '38px',
                      }}
                      className="max-w-full max-h-full bg-ui-elevated/90 border border-ui-strong/75 group-hover:border-ui-accent rounded-[1.5px] relative flex items-center justify-center transition-colors"
                    >
                      {preset.colorMode === 'monochrome' && (
                        <span
                          aria-hidden="true"
                          className="absolute inset-[3px] border border-dashed border-ui-muted/60"
                        />
                      )}
                    </div>
                    <span className="absolute bottom-1 right-1.5 text-[8.5px] font-ui-mono tabular-nums text-ui-muted">
                      {preset.tag}
                    </span>
                  </div>

                  {/* Title & Exact Technical Spec */}
                  <div className="text-[11.5px] font-medium text-ui-primary truncate leading-tight">
                    {td(preset.label)}
                  </div>
                  <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted mt-0.5 truncate">
                    {preset.width} × {preset.height} · {preset.dpi}dpi
                  </div>
                </button>
              );
            })}

            {/* Custom Canvas Tile */}
            <button
              type="button"
              data-testid="welcome-preset-custom"
              onClick={onNewDocument}
              className={`group flex flex-col text-left rounded-ui-md transition-colors cursor-pointer ${layout.cardPad} ${surfaceCardChrome}`}
            >
              <div className="w-full h-14 rounded-ui-xs bg-ui-input/60 border border-dashed border-ui-default group-hover:border-ui-accent/70 flex items-center justify-center p-2 mb-2 transition-colors">
                <div className="w-7 h-7 rounded-ui-xs border border-ui-subtle group-hover:border-ui-accent/60 bg-ui-panel flex items-center justify-center text-ui-icon-muted group-hover:text-ui-accent transition-colors">
                  <Plus className="w-3.5 h-3.5" />
                </div>
              </div>
              <div className="text-[11.5px] font-medium text-ui-primary truncate leading-tight">
                {t('Custom...')}
              </div>
              <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted mt-0.5 truncate">
                {t('Size, DPI & mode')}
              </div>
            </button>
          </div>
        </section>

        {/* 2. Pinned / Starred Projects */}
        {starredDocs.length > 0 && (
          <section aria-label={t('Pinned Projects')} className="space-y-2.5">
            <div className="flex items-center justify-between border-b border-ui-subtle pb-1.5">
              <div className="flex items-center gap-1.5">
                <Star className="w-3 h-3 text-ui-warning fill-current" />
                <h2 className="text-[10.5px] font-medium uppercase tracking-[0.08em] text-ui-muted">
                  {t('Pinned')}
                </h2>
              </div>
              <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
                {starredDocs.length}
              </span>
            </div>
            <div className={`grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 ${layout.gridGap}`}>
              {starredDocs.map((doc) => (
                <DocCard
                  key={`starred-${doc.id}`}
                  doc={doc}
                  cardPad={layout.cardPad}
                  surfaceClass={surfaceCardChrome}
                  onSelect={() =>
                    onSelectRecentDocument ? onSelectRecentDocument(doc) : onOpenFile()
                  }
                  onToggleStar={(e) => handleToggleStar(doc, e)}
                  onDelete={(e) => handleOpenDelete(doc, e)}
                />
              ))}
            </div>
          </section>
        )}

        {/* 3. Recent Projects Gallery */}
        <section aria-label={t('Recent Projects')} className="space-y-2.5 flex-1 flex flex-col">
          <div className="flex items-center justify-between border-b border-ui-subtle pb-1.5">
            <h2 className="text-[10.5px] font-medium uppercase tracking-[0.08em] text-ui-muted">
              {t('Recent Projects')}
            </h2>
            <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
              {filtered.length === 1
                ? t('{n} file', { n: filtered.length })
                : t('{n} files', { n: filtered.length })}
            </span>
          </div>

          {filtered.length === 0 ? (
            <div
              data-testid="welcome-empty-state"
              className="bg-ui-panel/90 border border-ui-subtle rounded-ui-md px-6 py-10 flex flex-col items-center justify-center text-center"
            >
              <div className="w-11 h-12 rounded-ui-xs bg-ui-input border border-ui-default flex flex-col items-center justify-center gap-1 mb-3">
                <span className="w-5 h-px bg-ui-strong" />
                <span className="w-6 h-px bg-ui-default" />
                <span className="w-4 h-px bg-ui-subtle" />
              </div>
              <p className="text-xs font-medium text-ui-primary">
                {cleanQuery
                  ? t('No projects matching "{query}"', { query: searchQuery.trim() })
                  : t('Your drafting table is clear')}
              </p>
              <p className="text-[11px] text-ui-muted mt-1 max-w-sm">
                {cleanQuery
                  ? t('Try a different filename or clear the search filter.')
                  : t('Pick a quick-start sheet above or open an existing .ink, .psd, or image file.')}
              </p>
              <div className="flex items-center gap-2 mt-4">
                {cleanQuery ? (
                  <button
                    type="button"
                    onClick={() => setSearchQuery('')}
                    className="h-[var(--ui-control-height)] px-3 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[11px] text-ui-primary transition-colors cursor-pointer"
                  >
                    {t('Clear Filter')}
                  </button>
                ) : (
                  <>
                    <button
                      type="button"
                      onClick={onNewDocument}
                      className="h-[var(--ui-control-height)] flex items-center gap-1.5 px-3 rounded-ui-sm bg-ui-accent text-ui-accent-contrast text-[11px] font-medium hover:opacity-90 transition-opacity cursor-pointer"
                    >
                      <FilePlus className="w-3.5 h-3.5" />
                      <span>{t('New Canvas')}</span>
                    </button>
                    <button
                      type="button"
                      onClick={onOpenFile}
                      className="h-[var(--ui-control-height)] flex items-center gap-1.5 px-3 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[11px] text-ui-primary transition-colors cursor-pointer"
                    >
                      <FolderOpen className="w-3.5 h-3.5 text-ui-icon-muted" />
                      <span>{t('Open File')}</span>
                    </button>
                  </>
                )}
              </div>
            </div>
          ) : (
            <div className={`grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 ${layout.gridGap}`}>
              {filtered.map((doc) => (
                <DocCard
                  key={`recent-${doc.id}`}
                  doc={doc}
                  cardPad={layout.cardPad}
                  surfaceClass={surfaceCardChrome}
                  onSelect={() =>
                    onSelectRecentDocument ? onSelectRecentDocument(doc) : onOpenFile()
                  }
                  onToggleStar={(e) => handleToggleStar(doc, e)}
                  onDelete={(e) => handleOpenDelete(doc, e)}
                />
              ))}
            </div>
          )}
        </section>

        {/* Quiet Atelier Community Footer */}
        <footer
          data-testid="welcome-community-footer"
          data-chrome-style={chromeStyle}
          className={`mt-auto flex flex-wrap items-center justify-between gap-2 ${footerChrome}`}
        >
          <span className="text-[10px] font-ui-mono text-ui-muted">
            {t('Ink Studio · Free & Open Source')}
          </span>
          <nav
            aria-label={t('Community and support links')}
            className="flex flex-wrap items-center gap-1"
          >
            {COMMUNITY_LINKS.map((link) => (
              <a
                key={`footer-${link.id}`}
                href={link.url}
                target="_blank"
                rel="noopener noreferrer"
                data-testid={`welcome-footer-${link.id}`}
                onClick={(e) => {
                  e.preventDefault();
                  void openExternalUrl(link.url);
                }}
                title={td(link.title)}
                className={footerLinkChrome}
              >
                {link.renderIcon('w-3 h-3 shrink-0')}
                <span>{td(link.label)}</span>
              </a>
            ))}
            <a
              href={GITHUB_ISSUES_URL}
              target="_blank"
              rel="noopener noreferrer"
              data-testid="welcome-footer-issues"
              onClick={(e) => {
                e.preventDefault();
                void openExternalUrl(GITHUB_ISSUES_URL);
              }}
              title={t('Report a bug or request a feature on GitHub')}
              className={footerLinkChrome}
            >
              <Bug className="w-3 h-3 shrink-0" />
              <span>{t('Issues')}</span>
            </a>
          </nav>
        </footer>
      </main>

      <DeleteDocumentModal
        isOpen={isDeleteModalOpen}
        document={deleteTargetDoc}
        onClose={() => {
          setIsDeleteModalOpen(false);
          setDeleteTargetDoc(null);
        }}
        onHideFromApp={handleHideFromApp}
        onPermanentlyDelete={handlePermanentDelete}
      />
    </div>
  );
};

interface DocCardProps {
  doc: RecentDocument;
  cardPad: string;
  surfaceClass: string;
  onSelect: () => void;
  onToggleStar: (e: React.MouseEvent) => void;
  onDelete: (e: React.MouseEvent) => void;
}

const DocCard: React.FC<DocCardProps> = ({
  doc,
  cardPad,
  surfaceClass,
  onSelect,
  onToggleStar,
  onDelete,
}) => {
  const { t, formatRelativeTime } = useI18n();
  const extTag = formatExtensionTag(doc);
  const dateLabel = formatRelativeTime(doc.lastOpened);
  const hasDimensions =
    typeof doc.width === 'number' &&
    doc.width > 0 &&
    typeof doc.height === 'number' &&
    doc.height > 0;

  return (
    <div
      role="button"
      tabIndex={0}
      onClick={onSelect}
      onKeyDown={(e) => {
        if (isImeComposing(e)) return;
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          onSelect();
        }
      }}
      className={`group relative flex flex-col rounded-ui-md cursor-pointer transition-colors focus:outline-none focus-visible:border-ui-focus ${cardPad} ${surfaceClass}`}
      title={doc.path ? `${doc.title} — ${doc.path}` : doc.title}
    >
      {/* Aspect-Aware Framed Thumbnail Stage */}
      <div className="relative aspect-[4/3] bg-ui-void ui-layer-thumb-checker border border-ui-subtle overflow-hidden flex items-center justify-center rounded-ui-sm p-2 mb-2">
        {doc.coverUrl ? (
          <img
            src={doc.coverUrl}
            alt={doc.title}
            draggable={false}
            className="max-w-full max-h-full object-contain rounded-[1.5px] border border-ui-default/70 bg-white select-none pointer-events-none"
          />
        ) : (
          <div
            style={
              hasDimensions
                ? { aspectRatio: `${doc.width} / ${doc.height}` }
                : undefined
            }
            className="h-4/5 max-w-[82%] aspect-[3/4] bg-ui-elevated border border-ui-default rounded-[2px] flex items-center justify-center"
          >
            <span className="text-[9.5px] font-ui-mono tracking-wider text-ui-muted">
              {extTag}
            </span>
          </div>
        )}

        {/* Format Chip bottom-left */}
        <span className="pointer-events-none absolute bottom-1.5 left-1.5 px-1 py-px rounded-ui-xs bg-ui-floating border border-ui-subtle text-[8.5px] font-ui-mono tracking-wider text-ui-secondary">
          {extTag}
        </span>

        {/* Pin & Remove Controls top-right */}
        <div className="absolute top-1.5 right-1.5 flex items-center gap-1">
          <button
            type="button"
            onClick={onToggleStar}
            title={
              doc.isStarred
                ? t('Unpin {title}', { title: doc.title })
                : t('Pin {title}', { title: doc.title })
            }
            aria-label={
              doc.isStarred
                ? t('Unpin {title}', { title: doc.title })
                : t('Pin {title}', { title: doc.title })
            }
            aria-pressed={doc.isStarred}
            className={`w-5 h-5 rounded-ui-xs bg-ui-floating border border-ui-subtle flex items-center justify-center cursor-pointer transition-opacity ${
              doc.isStarred
                ? 'text-ui-warning opacity-100'
                : 'text-ui-muted opacity-0 group-hover:opacity-100 focus:opacity-100 hover:text-ui-warning'
            }`}
          >
            <Star className={`w-3 h-3 ${doc.isStarred ? 'fill-current' : ''}`} />
          </button>
          <button
            type="button"
            onClick={onDelete}
            title={t('Remove {title}', { title: doc.title })}
            aria-label={t('Remove {title}', { title: doc.title })}
            className="w-5 h-5 rounded-ui-xs bg-ui-floating border border-ui-subtle text-ui-muted hover:text-ui-danger flex items-center justify-center opacity-0 group-hover:opacity-100 focus:opacity-100 cursor-pointer transition-opacity"
          >
            <X className="w-3 h-3" />
          </button>
        </div>
      </div>

      {/* Title & Tabular Metadata Row */}
      <div className="text-[11.5px] font-medium text-ui-primary truncate leading-tight">
        {doc.title}
      </div>
      <div className="flex items-center justify-between gap-2 text-[10px] font-ui-mono tabular-nums text-ui-muted mt-1">
        <span className="truncate">
          {hasDimensions
            ? `${doc.width}×${doc.height} · ${formatFileSize(doc.size)}`
            : formatFileSize(doc.size)}
        </span>
        {dateLabel && <span className="shrink-0">{dateLabel}</span>}
      </div>
    </div>
  );
};