"use client";

import type { ReactNode } from "react";

import { Icon, type IconName } from "./icons";
import {
  approvals,
  archiveItems,
  assignedWork,
  kpiDefinitions,
  mentions,
  metrics,
  publishingCalendar,
  reports,
  riskItems,
  type Mention,
  type ScreenState,
  type Tone
} from "./mock-data";
import {
  ContentState,
  DataTable,
  FilterBar,
  MentionCard,
  MetricCard,
  MiniChart,
  SectionHeading,
  StatusLabel,
  Timeline,
  type TableRow
} from "./ui-components";

interface ScreenProperties {
  readonly state: ScreenState;
  readonly onOpenMention: (mention: Mention) => void;
  readonly onAction: (action: string) => void;
}

const quickActions: ReadonlyArray<{
  label: string;
  detail: string;
  icon: IconName;
  tone: Tone;
}> = [
  { label: "Create case", detail: "From a signal or mention", icon: "inbox", tone: "neutral" },
  { label: "Draft response", detail: "AI-grounded starting point", icon: "sparkles", tone: "ai" },
  { label: "Open crisis room", detail: "Coordinate urgent risk", icon: "warning", tone: "urgent" },
  { label: "Share brief", detail: "Secure executive link", icon: "publish", tone: "positive" },
  { label: "Schedule report", detail: "Lock period and audience", icon: "reports", tone: "neutral" }
] as const;

export function CommandCentre({
  state,
  onOpenMention,
  onAction,
  greetingName
}: ScreenProperties & { readonly greetingName: string }) {
  return (
    <ScreenFrame
      state={state}
      subject="command centre data"
      eyebrow="Tuesday · 28 July 2026"
      title={`Good morning, ${greetingName.split(/\s+/u)[0] ?? greetingName}`}
      description="Here is what changed, why it matters and what needs attention across Mind Interactive."
      actions={
        <>
          <button
            className="button-secondary"
            type="button"
            onClick={() => onAction("Share brief")}
          >
            <Icon name="publish" size={17} /> Share brief
          </button>
          <button type="button" onClick={() => onAction("Create case")}>
            <Icon name="plus" size={17} /> Create case
          </button>
        </>
      }
    >
      <section className="brief-card">
        <div className="brief-icon">
          <Icon name="sparkles" />
        </div>
        <div>
          <div className="card-kicker">Morning intelligence brief · AI-assisted</div>
          <h3>Community schedule questions are the only material risk acceleration.</h3>
          <p>
            Conversation increased across Soweto and Ekurhuleni after two unverified schedules
            circulated. Source diversity is moderate, but one Tier 1 article amplified the issue.
            Positive tourism and responsible-gambling coverage is offsetting overall sentiment.
          </p>
          <div className="brief-evidence">
            <StatusLabel label="6 evidence items" tone="ai" />
            <span>92% evidence confidence</span>
            <span>Updated 08:26 SAST</span>
          </div>
        </div>
        <button className="button-text" type="button" onClick={() => onOpenMention(mentions[3]!)}>
          Inspect evidence <Icon name="chevron" size={16} />
        </button>
      </section>

      <section aria-labelledby="performance-title">
        <SectionHeading
          title="Performance at a glance"
          description="Agreed indicators with current value, target context and seven-day movement."
        />
        <div id="performance-title" className="metric-grid">
          {metrics.map((metric) => (
            <MetricCard key={metric.label} {...metric} />
          ))}
        </div>
      </section>

      <div className="dashboard-columns">
        <section className="panel risk-panel">
          <SectionHeading
            title="Risk queue"
            description="Prioritised by velocity, impact, severity and unresolved exposure."
            actions={<button className="button-text">View all risks</button>}
          />
          <div className="stack-list">
            {riskItems.map((risk) => (
              <button
                className="risk-row"
                key={risk.title}
                type="button"
                onClick={() => onOpenMention(mentions[risk.tone === "urgent" ? 3 : 1]!)}
              >
                <span className={`risk-symbol risk-symbol-${risk.tone}`}>
                  <Icon name="warning" size={17} />
                </span>
                <span>
                  <strong>{risk.title}</strong>
                  <small>{risk.detail}</small>
                </span>
                <span className="risk-owner">
                  <StatusLabel label={risk.status} tone={risk.tone} />
                  <small>
                    {risk.owner} · {risk.age}
                  </small>
                </span>
                <Icon name="chevron" size={16} />
              </button>
            ))}
          </div>
        </section>

        <section className="panel sla-panel">
          <SectionHeading
            title="SLA warnings"
            description="Four cases need attention before 10:00."
          />
          <div className="sla-score">
            <div className="ring-progress" aria-label="91.4 percent SLA attainment">
              <span>91.4%</span>
              <small>attainment</small>
            </div>
            <div>
              <strong>3 at risk</strong>
              <span>1 breached</span>
              <span>Median response 38 min</span>
            </div>
          </div>
          <button
            className="button-secondary button-full"
            onClick={() => onAction("Review SLA queue")}
          >
            Review SLA queue
          </button>
        </section>
      </div>

      <div className="dashboard-columns equal-columns">
        <section className="panel">
          <SectionHeading title="Assigned work" description="Your work and delegated analysis." />
          <DataTable
            caption="Assigned work"
            columns={[
              { key: "task", label: "Task" },
              { key: "due", label: "Due" },
              { key: "status", label: "Status" }
            ]}
            rows={assignedWork.map((work): TableRow => ({
              id: work.task,
              cells: {
                task: (
                  <span className="primary-cell">
                    <strong>{work.task}</strong>
                    <small>
                      {work.module} · {work.owner}
                    </small>
                  </span>
                ),
                due: work.due,
                status: (
                  <StatusLabel
                    label={work.status}
                    tone={work.status === "In progress" ? "positive" : "neutral"}
                  />
                )
              }
            }))}
          />
        </section>
        <section className="panel">
          <SectionHeading
            title="Outstanding approvals"
            description="Items waiting for your team’s decision."
          />
          <div className="approval-list">
            {approvals.map((approval) => (
              <article key={approval.item}>
                <span className="channel-chip">{approval.channel}</span>
                <strong>{approval.item}</strong>
                <small>
                  {approval.stage} · requested by {approval.requestedBy}
                </small>
                <div>
                  <span>Waiting {approval.waiting}</span>
                  <button className="button-text" onClick={() => onAction("Review approval")}>
                    Review <Icon name="chevron" size={15} />
                  </button>
                </div>
              </article>
            ))}
          </div>
        </section>
      </div>

      <section>
        <SectionHeading
          title="One-click operational actions"
          description="Move from intelligence to accountable action without losing context."
        />
        <div className="action-grid">
          {quickActions.map((action) => (
            <button key={action.label} type="button" onClick={() => onAction(action.label)}>
              <span className={`action-icon action-${action.tone}`}>
                <Icon name={action.icon} />
              </span>
              <span>
                <strong>{action.label}</strong>
                <small>{action.detail}</small>
              </span>
              <Icon name="chevron" size={17} />
            </button>
          ))}
        </div>
      </section>

      <div className="dashboard-columns equal-columns">
        <section className="panel opportunity-panel">
          <SectionHeading
            title="Emerging opportunities"
            description="Positive themes and voices gaining relevance."
          />
          <article>
            <StatusLabel label="Rising theme" tone="positive" />
            <h3>Township tourism itineraries</h3>
            <p>
              Positive conversation is up 38% week on week, led by Soweto culture, food and local
              guides.
            </p>
            <MiniChart
              values={[12, 18, 16, 25, 31, 33, 42]}
              label="Township tourism theme growth"
              tone="positive"
              height={70}
            />
          </article>
          <article>
            <StatusLabel label="Creator momentum" tone="ai" />
            <h3>Local travel creators</h3>
            <p>Four Gauteng creators show strong relevance and brand-safety signals.</p>
          </article>
        </section>
        <section className="panel">
          <SectionHeading
            title="Recent media coverage"
            description="Latest source-diverse earned coverage."
            actions={<button className="button-text">Open Media Intelligence</button>}
          />
          <div className="compact-coverage">
            {mentions.slice(0, 4).map((mention) => (
              <button key={mention.id} type="button" onClick={() => onOpenMention(mention)}>
                <span className="source-mark">{mention.source.slice(0, 2).toUpperCase()}</span>
                <span>
                  <strong>{mention.title}</strong>
                  <small>
                    {mention.source} · {mention.location}
                  </small>
                </span>
                <StatusLabel
                  label={mention.sentiment}
                  tone={mention.sentiment === "Positive" ? "positive" : "neutral"}
                />
              </button>
            ))}
          </div>
        </section>
      </div>
    </ScreenFrame>
  );
}

export function ListenScreen(properties: ScreenProperties) {
  return (
    <ScreenFrame
      {...properties}
      subject="listening results"
      eyebrow="Intelligence Studio"
      title="Listen"
      description="Find narratives, explain movement and connect every insight to source evidence."
      actions={
        <button type="button" onClick={() => properties.onAction("Create monitor")}>
          <Icon name="plus" size={17} /> Create monitor
        </button>
      }
    >
      <FilterBar searchLabel="Search mentions, narratives or entities">
        <FilterSelect label="Period" value="Last 7 days" />
        <FilterSelect label="Geography" value="South Africa" />
        <FilterSelect label="Source" value="All sources" />
      </FilterBar>
      <div className="analysis-grid">
        <section className="panel chart-panel">
          <SectionHeading
            title="Conversation volume"
            description="3,842 mentions · 17% above the previous period"
            actions={<StatusLabel label="Anomaly detected" tone="warning" />}
          />
          <VolumeChart />
          <div className="chart-legend" aria-label="Chart legend">
            <span>
              <i className="legend-blue" /> Total mentions
            </span>
            <span>
              <i className="legend-red" /> Negative mentions
            </span>
          </div>
        </section>
        <section className="panel narrative-panel">
          <SectionHeading
            title="Narrative movement"
            description="AI-suggested clusters, awaiting analyst validation."
            actions={<StatusLabel label="AI-assisted" tone="ai" />}
          />
          {[
            ["Community schedule clarity", "+184%", "Urgent", "urgent"],
            ["Township tourism itineraries", "+38%", "Opportunity", "positive"],
            ["Responsible gambling education", "+24%", "Growing", "neutral"],
            ["Visitor economy resilience", "+11%", "Stable", "neutral"]
          ].map(([title, change, label, tone]) => (
            <button key={title} type="button">
              <span>
                <strong>{title}</strong>
                <small>{change} mention velocity</small>
              </span>
              <StatusLabel label={label!} tone={tone as Tone} />
              <Icon name="chevron" size={16} />
            </button>
          ))}
        </section>
      </div>
      <SectionHeading
        title="Representative mentions"
        description="Deduplicated results from the active monitor with source and licence context."
        actions={<span className="result-count">3,842 results</span>}
      />
      <div className="mention-grid">
        {mentions.map((mention) => (
          <MentionCard key={mention.id} mention={mention} onOpen={properties.onOpenMention} />
        ))}
      </div>
    </ScreenFrame>
  );
}

export function MediaScreen(properties: ScreenProperties) {
  const rows = mentions.map((mention): TableRow => ({
    id: mention.id,
    cells: {
      coverage: (
        <button
          className="table-link"
          type="button"
          onClick={() => properties.onOpenMention(mention)}
        >
          <strong>{mention.title}</strong>
          <small>{mention.source}</small>
        </button>
      ),
      geography: mention.location,
      prominence: mention.id === "mention-002" ? "Headline" : "Body mention",
      messages: mention.sentiment === "Positive" ? "2 of 3" : "0 of 3",
      sentiment: (
        <StatusLabel
          label={mention.sentiment}
          tone={
            mention.sentiment === "Positive"
              ? "positive"
              : mention.sentiment === "Negative"
                ? "warning"
                : "neutral"
          }
        />
      )
    }
  }));
  return (
    <ScreenFrame
      {...properties}
      subject="media coverage"
      eyebrow="Earned media"
      title="Media Intelligence"
      description="Understand coverage quality, message pull-through and the outlets shaping the story."
      actions={
        <button type="button" onClick={() => properties.onAction("Build media brief")}>
          <Icon name="sparkles" size={17} /> Build media brief
        </button>
      }
    >
      <div className="summary-strip">
        <SummaryStat label="Coverage" value="428 clips" detail="+16% vs previous period" />
        <SummaryStat label="Potential reach" value="8.4m" detail="Not verified audience" />
        <SummaryStat label="Quality score" value="74 / 100" detail="+8 points" />
        <SummaryStat label="Message pull-through" value="68%" detail="Target 70%" />
      </div>
      <FilterBar searchLabel="Search coverage, outlets or journalists">
        <FilterSelect label="Outlet tier" value="All tiers" />
        <FilterSelect label="Geography" value="All provinces" />
        <FilterSelect label="Coverage type" value="All media" />
      </FilterBar>
      <div className="media-insight-grid">
        <section className="panel">
          <SectionHeading
            title="Coverage by province"
            description="Location attributed from outlet and story context."
          />
          <ProvinceBars />
        </section>
        <section className="panel">
          <SectionHeading
            title="Message pull-through"
            description="Priority messages found in reviewed coverage."
          />
          <div className="message-bars">
            <Progress label="Local economic participation" value={78} />
            <Progress label="Clear public information" value={61} tone="warning" />
            <Progress label="Responsible participation" value={67} />
          </div>
        </section>
      </div>
      <section className="panel">
        <SectionHeading
          title="Coverage stream"
          description="Full text and visual evidence depend on source rights."
          actions={<StatusLabel label="Mock licensed feed" tone="neutral" />}
        />
        <DataTable
          caption="Earned media coverage"
          columns={[
            { key: "coverage", label: "Coverage" },
            { key: "geography", label: "Geography" },
            { key: "prominence", label: "Prominence" },
            { key: "messages", label: "Messages" },
            { key: "sentiment", label: "Sentiment" }
          ]}
          rows={rows}
        />
      </section>
    </ScreenFrame>
  );
}

export function InboxScreen(properties: ScreenProperties) {
  const cases = [
    {
      id: "CASE-1042",
      person: "Naledi M.",
      channel: "Facebook",
      subject: "Community engagement schedule",
      owner: "Lerato Khumalo",
      status: "Triage",
      tone: "urgent" as const,
      sla: "12 min left"
    },
    {
      id: "CASE-1041",
      person: "Kabelo R.",
      channel: "Instagram",
      subject: "Accessible tourism information",
      owner: "Lerato Khumalo",
      status: "Assigned",
      tone: "warning" as const,
      sla: "38 min left"
    },
    {
      id: "CASE-1039",
      person: "Thandi P.",
      channel: "X",
      subject: "Responsible gambling support",
      owner: "Neo Maseko",
      status: "Approval",
      tone: "ai" as const,
      sla: "1h 08m left"
    },
    {
      id: "CASE-1037",
      person: "Mpho S.",
      channel: "Facebook",
      subject: "Campaign dates confirmed",
      owner: "Neo Maseko",
      status: "Resolved",
      tone: "positive" as const,
      sla: "Met in 22 min"
    }
  ] as const;
  return (
    <ScreenFrame
      {...properties}
      subject="inbox cases"
      eyebrow="Response management"
      title="Inbox"
      description="Prioritise public conversations, protect service levels and keep every decision accountable."
      actions={
        <button type="button" onClick={() => properties.onAction("New case")}>
          <Icon name="plus" size={17} /> New case
        </button>
      }
    >
      <div className="inbox-stats">
        <StatusCount label="New" value="18" tone="neutral" />
        <StatusCount label="At risk" value="3" tone="warning" />
        <StatusCount label="Breached" value="1" tone="urgent" />
        <StatusCount label="Awaiting approval" value="6" tone="ai" />
        <StatusCount label="Resolved today" value="42" tone="positive" />
      </div>
      <FilterBar searchLabel="Search cases or people">
        <FilterSelect label="Queue" value="My team" />
        <FilterSelect label="Status" value="Open cases" />
        <FilterSelect label="Channel" value="All channels" />
      </FilterBar>
      <div className="inbox-layout">
        <section className="panel case-list" aria-label="Case queue">
          {cases.map((item, index) => (
            <button key={item.id} className={index === 0 ? "selected-case" : ""} type="button">
              <span className="avatar">{item.person.slice(0, 1)}</span>
              <span>
                <span className="case-title">
                  <strong>{item.person}</strong>
                  <small>{item.id}</small>
                </span>
                <b>{item.subject}</b>
                <small>
                  {item.channel} · {item.owner}
                </small>
              </span>
              <span className="case-status">
                <StatusLabel label={item.status} tone={item.tone} />
                <small>{item.sla}</small>
              </span>
            </button>
          ))}
        </section>
        <section className="panel conversation-panel">
          <header className="conversation-header">
            <div>
              <span className="section-eyebrow">CASE-1042 · FACEBOOK</span>
              <h2>Community engagement schedule</h2>
              <p>Naledi M. · Soweto, Gauteng · public comment</p>
            </div>
            <StatusLabel label="Triage · 12 min left" tone="urgent" />
          </header>
          <div className="message-thread">
            <article>
              <span className="avatar">N</span>
              <div>
                <strong>Naledi M.</strong>
                <time>08:14</time>
                <p>
                  Please confirm which community engagement date is correct. I have seen two
                  different posters for Soweto.
                </p>
              </div>
            </article>
            <article className="internal-note">
              <span className="avatar">T</span>
              <div>
                <strong>Thabo Molefe · Internal note</strong>
                <time>08:22</time>
                <p>
                  The approved programme lists 31 July. The second poster is not an authorised
                  asset. Evidence attached.
                </p>
              </div>
            </article>
          </div>
          <div className="ai-suggestion">
            <div>
              <Icon name="sparkles" />
              <strong>Grounded response suggestion</strong>
              <StatusLabel label="2 approved sources" tone="ai" />
            </div>
            <p>
              Thanks for checking, Naledi. The confirmed Soweto engagement is on 31 July. Please use
              the programme on our verified page; we are reporting the incorrect poster.
            </p>
            <small>AI suggestion · review required · never publishes automatically</small>
          </div>
          <label className="response-composer">
            <span>Response</span>
            <textarea
              rows={4}
              defaultValue="Thanks for checking, Naledi. The confirmed Soweto engagement is on 31 July."
            />
          </label>
          <div className="composer-actions">
            <button className="button-secondary" onClick={() => properties.onAction("Add note")}>
              Add internal note
            </button>
            <button onClick={() => properties.onAction("Request approval")}>
              Request approval
            </button>
          </div>
        </section>
      </div>
    </ScreenFrame>
  );
}

export function PublishScreen(properties: ScreenProperties) {
  return (
    <ScreenFrame
      {...properties}
      subject="publishing calendar"
      eyebrow="Content operations"
      title="Publish"
      description="Plan one campaign, tailor every channel and preserve the approved final record."
      actions={
        <button type="button" onClick={() => properties.onAction("Compose post")}>
          <Icon name="plus" size={17} /> Compose post
        </button>
      }
    >
      <div className="summary-strip">
        <SummaryStat label="Scheduled this week" value="24 posts" detail="4 channels" />
        <SummaryStat label="Awaiting approval" value="6" detail="Oldest 2h 05m" />
        <SummaryStat label="Publishing reliability" value="99.2%" detail="Target 99%" />
        <SummaryStat label="Rights expiring" value="2 assets" detail="Within 14 days" />
      </div>
      <div className="calendar-toolbar">
        <div className="segmented-control" aria-label="Calendar view">
          <button className="active" type="button">
            Week
          </button>
          <button type="button">Month</button>
          <button type="button">Campaign</button>
        </div>
        <FilterSelect label="Campaign" value="All campaigns" />
        <FilterSelect label="Channel" value="All channels" />
      </div>
      <section className="panel calendar-panel">
        <div className="calendar-days" aria-label="Publishing week">
          {["Mon 27", "Tue 28", "Wed 29", "Thu 30", "Fri 31"].map((day, dayIndex) => (
            <section key={day} className={dayIndex === 1 ? "today" : ""}>
              <header>
                <span>{day}</span>
                <small>{dayIndex === 1 ? "Today" : `${dayIndex + 2} posts`}</small>
              </header>
              {(dayIndex === 1
                ? publishingCalendar
                : publishingCalendar.slice(dayIndex % 2, (dayIndex % 2) + 2)
              ).map((post) => (
                <button
                  key={`${day}-${post.time}-${post.title}`}
                  className={`calendar-event event-${post.tone}`}
                  onClick={() => properties.onAction("Review post")}
                >
                  <time>{post.time}</time>
                  <strong>{post.title}</strong>
                  <small>{post.channels}</small>
                  <StatusLabel label={post.status} tone={post.tone} />
                </button>
              ))}
            </section>
          ))}
        </div>
      </section>
      <div className="dashboard-columns equal-columns">
        <section className="panel">
          <SectionHeading
            title="Approval pipeline"
            description="Draft → review → legal → final approval → schedule."
          />
          <Timeline
            items={[
              {
                time: "08:12",
                title: "Service update holding copy",
                detail: "Communications approval · Palesa Dube",
                tone: "warning"
              },
              {
                time: "07:50",
                title: "Responsible Gambling Week",
                detail: "Legal approval · 38 minutes waiting",
                tone: "ai"
              },
              {
                time: "Yesterday",
                title: "Winter in Gauteng: Soweto",
                detail: "Approved and scheduled",
                tone: "positive"
              }
            ]}
          />
        </section>
        <section className="panel">
          <SectionHeading title="Asset readiness" description="Rights, alt text and variants." />
          <Progress label="Assets with alt text" value={96} />
          <Progress label="Current usage rights" value={92} tone="warning" />
          <Progress label="Network variants ready" value={88} />
        </section>
      </div>
    </ScreenFrame>
  );
}

export function ArchiveScreen(properties: ScreenProperties) {
  return (
    <ScreenFrame
      {...properties}
      subject="archive records"
      eyebrow="Evidence-grade records"
      title="Evidence Archive"
      description="Find the source, action, approval and integrity history behind every communication."
      actions={
        <button type="button" onClick={() => properties.onAction("Create evidence bundle")}>
          <Icon name="archive" size={17} /> Create evidence bundle
        </button>
      }
    >
      <div className="archive-assurance">
        <span className="assurance-icon">
          <Icon name="check" />
        </span>
        <div>
          <strong>Archive integrity healthy</strong>
          <p>18,492 records verified · last integrity check today at 03:00 SAST</p>
        </div>
        <StatusLabel label="All hashes verified" tone="positive" />
      </div>
      <FilterBar searchLabel="Search content, cases, approvals or evidence IDs">
        <FilterSelect label="Record type" value="All records" />
        <FilterSelect label="Retention" value="All policies" />
        <FilterSelect label="Period" value="Last 90 days" />
      </FilterBar>
      <section className="panel">
        <SectionHeading
          title="Recent archive records"
          description="Captured content is fictional and permitted for development use."
          actions={<StatusLabel label="Mock evidence store" tone="neutral" />}
        />
        <DataTable
          caption="Evidence archive records"
          columns={[
            { key: "record", label: "Record" },
            { key: "type", label: "Type" },
            { key: "captured", label: "Captured" },
            { key: "retention", label: "Retention" },
            { key: "integrity", label: "Integrity" },
            { key: "actions", label: "", align: "right" }
          ]}
          rows={archiveItems.map((item): TableRow => ({
            id: item.id,
            cells: {
              record: (
                <span className="primary-cell">
                  <strong>{item.title}</strong>
                  <small>{item.id}</small>
                </span>
              ),
              type: item.type,
              captured: item.captured,
              retention: (
                <span className="primary-cell">
                  <span>{item.retention}</span>
                  <small>{item.hold}</small>
                </span>
              ),
              integrity: <StatusLabel label={item.integrity} tone="positive" />,
              actions: (
                <button
                  className="button-text"
                  onClick={() => properties.onAction("Inspect evidence record")}
                >
                  Inspect
                </button>
              )
            }
          }))}
        />
      </section>
      <div className="dashboard-columns equal-columns">
        <section className="panel">
          <SectionHeading
            title="Retention overview"
            description="Policy-aware, never forever by default."
          />
          <div className="retention-grid">
            <SummaryStat label="Standard records" value="14,206" detail="5–7 year policies" />
            <SummaryStat label="Licence-based" value="3,918" detail="Provider-specific" />
            <SummaryStat label="Legal hold" value="28" detail="Deletion suspended" />
            <SummaryStat label="Tombstones" value="340" detail="Permitted metadata only" />
          </div>
        </section>
        <section className="panel">
          <SectionHeading title="Evidence bundles" description="Governed exports with manifests." />
          <Timeline
            items={[
              {
                time: "Today",
                title: "July community response audit",
                detail: "48 records · expires 4 Aug 2026",
                tone: "positive"
              },
              {
                time: "25 Jul",
                title: "Winter campaign steering pack",
                detail: "112 records · watermarked",
                tone: "neutral"
              },
              {
                time: "18 Jul",
                title: "Service incident review",
                detail: "Legal hold applied",
                tone: "warning"
              }
            ]}
          />
        </section>
      </div>
    </ScreenFrame>
  );
}

export function KpiScreen(properties: ScreenProperties) {
  return (
    <ScreenFrame
      {...properties}
      subject="KPI definitions"
      eyebrow="Governed measurement"
      title="KPI Studio"
      description="Define what success means, how it is calculated and which evidence supports it."
      actions={
        <button type="button" onClick={() => properties.onAction("Define KPI")}>
          <Icon name="plus" size={17} /> Define KPI
        </button>
      }
    >
      <div className="metric-grid">
        {metrics.slice(0, 6).map((metric) => (
          <MetricCard key={metric.label} {...metric} />
        ))}
      </div>
      <div className="kpi-layout">
        <section className="panel kpi-list">
          <SectionHeading
            title="KPI dictionary"
            description="Versioned definitions currently active in this workspace."
          />
          {kpiDefinitions.map((kpi, index) => (
            <button key={kpi.name} className={index === 0 ? "selected-kpi" : ""} type="button">
              <span>
                <strong>{kpi.name}</strong>
                <small>{kpi.purpose}</small>
              </span>
              <StatusLabel label={kpi.confidence} tone={index === 1 ? "positive" : "neutral"} />
              <Icon name="chevron" size={16} />
            </button>
          ))}
        </section>
        <section className="panel kpi-detail">
          <span className="section-eyebrow">ACTIVE DEFINITION · VERSION 3</span>
          <h2>Reputation risk index</h2>
          <p>Tracks the weighted exposure to emerging reputation harm.</p>
          <dl className="definition-grid">
            <div>
              <dt>Formula</dt>
              <dd>{kpiDefinitions[0].formula}</dd>
            </div>
            <div>
              <dt>Target</dt>
              <dd>{kpiDefinitions[0].target}</dd>
            </div>
            <div>
              <dt>Owner</dt>
              <dd>{kpiDefinitions[0].owner}</dd>
            </div>
            <div>
              <dt>Cadence</dt>
              <dd>{kpiDefinitions[0].cadence}</dd>
            </div>
            <div>
              <dt>Accepted sources</dt>
              <dd>Online news, Facebook, Instagram, X and TikTok mock connectors</dd>
            </div>
            <div>
              <dt>Coverage caveat</dt>
              <dd>Potential reach is not verified audience. Sentiment remains directional.</dd>
            </div>
          </dl>
          <div className="formula-breakdown">
            {[
              ["Negative velocity", 25, 42],
              ["Source impact", 20, 31],
              ["Narrative severity", 20, 38],
              ["Cross-channel spread", 15, 28],
              ["Stakeholder sensitivity", 10, 45],
              ["Unresolved exposure", 10, 22]
            ].map(([label, weight, value]) => (
              <Progress
                key={String(label)}
                label={`${String(label)} · ${String(weight)}% weight`}
                value={Number(value)}
                tone={Number(value) > 40 ? "warning" : "neutral"}
              />
            ))}
          </div>
        </section>
      </div>
    </ScreenFrame>
  );
}

export function ReportsScreen(properties: ScreenProperties) {
  return (
    <ScreenFrame
      {...properties}
      subject="reports"
      eyebrow="Accountable reporting"
      title="Reports"
      description="Explore live dashboards or lock a period for reproducible executive reporting."
      actions={
        <button type="button" onClick={() => properties.onAction("Create report")}>
          <Icon name="plus" size={17} /> Create report
        </button>
      }
    >
      <div className="report-feature">
        <div>
          <StatusLabel label="Ready for review" tone="ai" />
          <span className="card-kicker">Weekly reputation report</span>
          <h2>A calmer risk picture, with one operational exception</h2>
          <p>
            The draft narrative is grounded in 428 media clips, 3,842 monitored mentions and 126
            resolved cases. Every number links to its KPI definition and locked data cut-off.
          </p>
          <div className="report-actions">
            <button onClick={() => properties.onAction("Review report")}>Review draft</button>
            <button
              className="button-secondary"
              onClick={() => properties.onAction("Inspect sources")}
            >
              Inspect sources
            </button>
          </div>
        </div>
        <div className="report-preview" aria-label="Report preview">
          <span>MI-INSITE WEEKLY BRIEF</span>
          <strong>Reputation &amp; response</strong>
          <MiniChart
            values={[52, 48, 46, 47, 42, 40, 34]}
            label="Report reputation risk trend"
            tone="positive"
            height={82}
          />
          <div>
            <b>34</b>
            <small>risk index</small>
            <b>91%</b>
            <small>SLA</small>
          </div>
        </div>
      </div>
      <section className="panel">
        <SectionHeading
          title="Report library"
          description="Live dashboards, scheduled reports and fixed-period accountability records."
        />
        <DataTable
          caption="Report library"
          columns={[
            { key: "report", label: "Report" },
            { key: "audience", label: "Audience" },
            { key: "schedule", label: "Schedule" },
            { key: "cutoff", label: "Data cut-off" },
            { key: "status", label: "Status" },
            { key: "actions", label: "", align: "right" }
          ]}
          rows={reports.map((report): TableRow => ({
            id: report.name,
            cells: {
              report: (
                <span className="primary-cell">
                  <strong>{report.name}</strong>
                  <small>PDF · secure link · CSV appendix</small>
                </span>
              ),
              audience: report.audience,
              schedule: report.schedule,
              cutoff: report.cutOff,
              status: (
                <StatusLabel
                  label={report.status}
                  tone={
                    report.status === "Delivered"
                      ? "positive"
                      : report.status.includes("review")
                        ? "ai"
                        : "neutral"
                  }
                />
              ),
              actions: <button className="button-text">Open</button>
            }
          }))}
        />
      </section>
      <section>
        <SectionHeading
          title="Templates"
          description="Start with a governed reporting structure."
        />
        <div className="template-grid">
          {[
            ["Morning brief", "Daily priorities in five minutes", "brief"],
            ["Reputation report", "Narratives, risk and response", "reports"],
            ["Campaign report", "Owned, earned and outcome KPIs", "kpi"],
            ["Crisis review", "Timeline, decisions and containment", "warning"]
          ].map(([title, detail, icon]) => (
            <button key={title} onClick={() => properties.onAction(`Create ${title}`)}>
              <Icon name={icon as IconName} />
              <span>
                <strong>{title}</strong>
                <small>{detail}</small>
              </span>
              <Icon name="plus" size={16} />
            </button>
          ))}
        </div>
      </section>
    </ScreenFrame>
  );
}

export function SettingsScreen(properties: ScreenProperties) {
  return (
    <ScreenFrame
      {...properties}
      subject="workspace settings"
      eyebrow="Workspace governance"
      title="Settings"
      description="Manage the workspace, sources, taxonomy and policies without weakening tenant boundaries."
      actions={
        <button type="button" onClick={() => properties.onAction("Save settings")}>
          <Icon name="check" size={17} /> Save changes
        </button>
      }
    >
      <div className="settings-layout">
        <nav className="panel settings-nav" aria-label="Settings sections">
          {[
            ["Workspace profile", "settings"],
            ["Members & roles", "inbox"],
            ["Connectors", "listen"],
            ["Taxonomy", "filter"],
            ["SLA & routing", "warning"],
            ["Approvals", "check"],
            ["Retention", "archive"],
            ["Audit log", "document"]
          ].map(([label, icon], index) => (
            <button className={index === 0 ? "active" : ""} key={label} type="button">
              <Icon name={icon as IconName} size={18} />
              {label}
              <Icon name="chevron" size={15} />
            </button>
          ))}
        </nav>
        <section className="panel settings-form">
          <SectionHeading
            title="Workspace profile"
            description="Applied only to Corporate Reputation in Mind Interactive."
          />
          <div className="form-grid">
            <label>
              Workspace name
              <input defaultValue="Corporate Reputation" />
            </label>
            <label>
              Default language
              <select defaultValue="en-ZA">
                <option value="en-ZA">English (South Africa)</option>
              </select>
            </label>
            <label>
              Timezone
              <select defaultValue="Africa/Johannesburg">
                <option value="Africa/Johannesburg">Africa/Johannesburg (SAST)</option>
              </select>
            </label>
            <label>
              Reporting week
              <select defaultValue="monday">
                <option value="monday">Monday to Sunday</option>
              </select>
            </label>
          </div>
          <fieldset>
            <legend>South African geography defaults</legend>
            <label className="check-control">
              <input type="checkbox" defaultChecked />
              <span>
                <strong>Use province and municipality hierarchy</strong>
                <small>Province → district/metropolitan municipality → locality</small>
              </span>
            </label>
            <label className="check-control">
              <input type="checkbox" defaultChecked />
              <span>
                <strong>Show SAST on operational timers</strong>
                <small>UTC remains preserved in source metadata and evidence exports</small>
              </span>
            </label>
          </fieldset>
          <fieldset>
            <legend>Mock connector status</legend>
            <div className="connector-grid">
              {["Facebook", "Instagram", "X", "TikTok", "Online news"].map((connector) => (
                <article key={connector}>
                  <span className="source-mark">{connector.slice(0, 2).toUpperCase()}</span>
                  <span>
                    <strong>{connector}</strong>
                    <small>Synthetic development data</small>
                  </span>
                  <StatusLabel label="Healthy mock" tone="positive" />
                </article>
              ))}
            </div>
          </fieldset>
        </section>
      </div>
    </ScreenFrame>
  );
}

function ScreenFrame({
  state,
  subject,
  eyebrow,
  title,
  description,
  actions,
  children
}: {
  readonly state: ScreenState;
  readonly subject: string;
  readonly eyebrow: string;
  readonly title: string;
  readonly description: string;
  readonly actions?: ReactNode;
  readonly children: ReactNode;
}) {
  return (
    <>
      <SectionHeading eyebrow={eyebrow} title={title} description={description} actions={actions} />
      <ContentState state={state} subject={subject}>
        <div className="screen-content">{children}</div>
      </ContentState>
    </>
  );
}

function FilterSelect({ label, value }: { readonly label: string; readonly value: string }) {
  return (
    <label className="filter-select">
      <span className="visually-hidden">{label}</span>
      <select aria-label={label} defaultValue={value}>
        <option>{value}</option>
      </select>
    </label>
  );
}

function SummaryStat({
  label,
  value,
  detail
}: {
  readonly label: string;
  readonly value: string;
  readonly detail: string;
}) {
  return (
    <div className="summary-stat">
      <span>{label}</span>
      <strong>{value}</strong>
      <small>{detail}</small>
    </div>
  );
}

function StatusCount({
  label,
  value,
  tone
}: {
  readonly label: string;
  readonly value: string;
  readonly tone: Tone;
}) {
  return (
    <div className={`status-count count-${tone}`}>
      <strong>{value}</strong>
      <span>{label}</span>
    </div>
  );
}

function Progress({
  label,
  value,
  tone = "positive"
}: {
  readonly label: string;
  readonly value: number;
  readonly tone?: Tone;
}) {
  return (
    <div className="progress-row">
      <div>
        <span>{label}</span>
        <strong>{value}%</strong>
      </div>
      <div
        className={`progress-track progress-${tone}`}
        role="progressbar"
        aria-label={label}
        aria-valuemin={0}
        aria-valuemax={100}
        aria-valuenow={value}
      >
        <span style={{ width: `${value}%` }} />
      </div>
    </div>
  );
}

function VolumeChart() {
  const total =
    "0,136 28,126 56,130 84,108 112,112 140,92 168,100 196,68 224,78 252,42 280,55 308,28 336,47 364,22 392,38 420,18 448,31 476,12 504,29 532,20 560,26";
  const negative =
    "0,148 28,146 56,150 84,142 112,145 140,136 168,140 196,124 224,132 252,105 280,120 308,89 336,108 364,72 392,96 420,62 448,81 476,48 504,73 532,61 560,68";
  return (
    <svg
      className="volume-chart"
      viewBox="0 0 560 170"
      role="img"
      aria-labelledby="volume-chart-title volume-chart-description"
    >
      <title id="volume-chart-title">Conversation volume over seven days</title>
      <desc id="volume-chart-description">
        Total mentions and negative mentions both rise sharply on 28 July.
      </desc>
      {[20, 60, 100, 140].map((y) => (
        <line key={y} x1="0" x2="560" y1={y} y2={y} />
      ))}
      <polyline className="line-total" points={total} />
      <polyline className="line-negative" points={negative} />
      <circle className="chart-point" cx="476" cy="12" r="5" />
      <text x="438" y="35">
        +184% spike
      </text>
    </svg>
  );
}

function ProvinceBars() {
  const provinces = [
    ["Gauteng", 72],
    ["Western Cape", 44],
    ["KwaZulu-Natal", 38],
    ["Eastern Cape", 24],
    ["Limpopo", 18]
  ] as const;
  return (
    <div className="province-bars">
      {provinces.map(([province, value]) => (
        <div key={province}>
          <span>{province}</span>
          <div>
            <i style={{ width: `${value}%` }} />
          </div>
          <strong>{value}%</strong>
        </div>
      ))}
    </div>
  );
}
