export type RequirementStatus = "ready" | "blocked" | "not_connected" | "not_started" | "waiting";
export type ProductRequirementTab =
  | "product-core"
  | "discovery"
  | "playback"
  | "account"
  | "accessibility"
  | "telemetry"
  | "compliance"
  | "qa-matrix";

export type RequirementRow = {
  id: string;
  area: string;
  requirement: string;
  common: string;
  platformSpecific: string;
  status: RequirementStatus;
  evidence: string;
};

export type OttProductRequirements = {
  appId: string;
  tab: ProductRequirementTab;
  title: string;
  summary: string;
  rows: RequirementRow[];
};

const commonCore: RequirementRow[] = [
  {
    id: "account_profile_sync",
    area: "Account",
    requirement: "Account, profile and device sync",
    common: "Accounts, profiles, watch history, continue watching, watchlist, parental controls and entitlement state must sync across devices.",
    platformSpecific: "Selected app must expose this through the platform-appropriate login/session model.",
    status: "blocked",
    evidence: "API contract, session model, device QA"
  },
  {
    id: "entitlements",
    area: "Entitlements",
    requirement: "Subscription and entitlement checks",
    common: "Every app must verify subscription, plan, rental/purchase access where applicable, region rules and parental access before playback.",
    platformSpecific: "Store-specific purchase/restore flows are platform-specific.",
    status: "blocked",
    evidence: "Entitlement API, store integration, test user"
  },
  {
    id: "playback_state",
    area: "Playback",
    requirement: "Resume and playback state",
    common: "Resume point, play progress, next episode, skip intro/recap, subtitles, audio tracks and error recovery must behave consistently.",
    platformSpecific: "Control placement and media keys change by device input model.",
    status: "blocked",
    evidence: "Player QA matrix"
  },
  {
    id: "search_deeplinks",
    area: "Discovery",
    requirement: "Search, suggestions and deep links",
    common: "Search, suggestions, filters where suitable, title/collection/campaign deep links and no-results recovery must be supported.",
    platformSpecific: "TV minimizes typing; web/mobile can support richer search and filters.",
    status: "blocked",
    evidence: "Search API, deep link map"
  },
  {
    id: "accessibility_localization",
    area: "Accessibility",
    requirement: "Accessibility, captions and localization",
    common: "Readable typography, focus/keyboard/remote accessibility, captions, subtitles, audio language and localization must be planned.",
    platformSpecific: "Screen reader, focus engine, remote focus and platform caption surfaces differ.",
    status: "blocked",
    evidence: "Accessibility checklist"
  },
  {
    id: "analytics_health",
    area: "Telemetry",
    requirement: "Analytics, health and crash/error telemetry",
    common: "Browse, search, playback, buffering, ad/subscription funnel, exits, errors and crash/health must be recorded only from real integrations.",
    platformSpecific: "Store dashboards and native vitals differ per platform.",
    status: "not_connected",
    evidence: "Telemetry SDK/API credentials"
  }
];

function mobileRows(appId: string): RequirementRow[] {
  const isIOS = appId === "ios-mobile";
  return [
    {
      id: "mobile_bottom_nav",
      area: "Navigation",
      requirement: "Touch-first navigation",
      common: "Mobile must optimize quick sessions and one-handed flows.",
      platformSpecific: isIOS ? "Use iOS-native navigation stack, tab patterns, safe areas and review-safe account/payment flows." : "Use Android bottom navigation, app bar, system back stack, Material-style touch behavior and media session readiness.",
      status: "blocked",
      evidence: "Mobile UX spec and device QA"
    },
    {
      id: "mobile_device_features",
      area: "Device features",
      requirement: "Downloads, push, lifecycle and share",
      common: "Mobile apps can support downloads/offline, push notifications, biometric re-entry, share links and network-aware quality.",
      platformSpecific: isIOS ? "iOS AirPlay/PiP/lock-screen behavior must follow Apple expectations." : "Android media session, casting/PiP where scoped, notification channels and storage controls required.",
      status: "blocked",
      evidence: "Native shell plan"
    }
  ];
}

function tabletRows(appId: string): RequirementRow[] {
  const label = appId === "ipados" ? "iPadOS" : appId === "android-tablet" ? "Android tablet" : "tablet";
  return [
    {
      id: "tablet_adaptive_layout",
      area: "Layout",
      requirement: "Adaptive tablet/foldable layout",
      common: "Tablet must not be scaled phone UI; it needs larger canvas, rails or split view and richer browsing density.",
      platformSpecific: `${label} requires multi-pane browse/detail, landscape support, optional keyboard/pointer and resize/multitasking-safe playback.`,
      status: "blocked",
      evidence: "Tablet layout QA"
    },
    {
      id: "tablet_density",
      area: "Discovery",
      requirement: "Hybrid discovery density",
      common: "Tablet should show more content and metadata than phone but remain less dense than desktop.",
      platformSpecific: "Use balanced row width, contextual metadata panes and larger preview surfaces.",
      status: "blocked",
      evidence: "Tablet discovery design"
    }
  ];
}

function tvRows(appId: string): RequirementRow[] {
  const partnerWaiting = ["gaiaos", "vizio", "vidaa"].includes(appId);
  return [
    {
      id: "tv_10foot",
      area: "TV UX",
      requirement: "10-foot UI and remote-first navigation",
      common: "TV/device apps must prioritize distance readability, large cards, low text, clear focus and D-pad/remote flow.",
      platformSpecific: partnerWaiting ? "Partner/OEM runtime and certification details are waiting; still enforce remote-first 10-foot UX now." : "Use the platform focus engine, TV-safe overscan, row/rail browsing and remote media keys.",
      status: partnerWaiting ? "waiting" : "blocked",
      evidence: "TV device QA"
    },
    {
      id: "tv_login",
      area: "Login",
      requirement: "Low-friction TV sign-in",
      common: "TV apps should avoid long password entry; prefer code pairing, QR/device login or ecosystem-assisted sign-in where available.",
      platformSpecific: "Selected TV platform must document its pairing/login pattern and review-safe test account process.",
      status: "blocked",
      evidence: "TV login spec"
    },
    {
      id: "tv_playback",
      area: "Playback",
      requirement: "Remote-compatible player",
      common: "Transport controls, subtitles/audio, buffering/error states, resume and next episode must be readable and D-pad compatible.",
      platformSpecific: "Player control placement and remote keys must match platform conventions.",
      status: "blocked",
      evidence: "TV playback QA"
    },
    {
      id: "tv_certification",
      area: "Store / Certification",
      requirement: "Platform store/OEM certification",
      common: "Every TV/device app needs platform listing assets, privacy/support URLs, test credentials, device QA and certification checklist.",
      platformSpecific: partnerWaiting ? "Private OEM checklist not assumed; show waiting-for-details until official requirements are received." : "Follow platform store or certification submission path.",
      status: partnerWaiting ? "waiting" : "blocked",
      evidence: "Store/OEM checklist"
    }
  ];
}

function webRows(): RequirementRow[] {
  return [
    {
      id: "web_rich_discovery",
      area: "Web discovery",
      requirement: "Rich web discovery and account surface",
      common: "Web is the richest surface for account, payments, campaign landing pages, SEO where applicable and advanced catalog browsing.",
      platformSpecific: "Use compact app-style layout, keyboard/hover/focus states, advanced filters, editorial collections and metadata depth.",
      status: "blocked",
      evidence: "Web UX spec"
    },
    {
      id: "web_commercial",
      area: "Commercial",
      requirement: "Payments, plan and account management",
      common: "Web should handle subscription signup, coupon, invoice, upgrade/downgrade, cancel/reactivate and payment failure recovery.",
      platformSpecific: "Store-native platforms may restrict payment messaging; web remains the full commercial surface.",
      status: "blocked",
      evidence: "Commerce flow QA"
    }
  ];
}

function platformRows(appId: string): RequirementRow[] {
  if (appId === "web-pwa") return webRows();
  if (["android-mobile", "ios-mobile"].includes(appId)) return mobileRows(appId);
  if (["android-tablet", "ipados", "chromeos-tablet", "fire-tablet", "windows-tablet"].includes(appId)) return tabletRows(appId);
  return tvRows(appId);
}

function rowsForTab(appId: string, tab: ProductRequirementTab): RequirementRow[] {
  const all = [...commonCore, ...platformRows(appId)];

  if (tab === "product-core") return commonCore;
  if (tab === "discovery") return all.filter((r) => /Discovery|Search|Web discovery|TV UX|Layout/.test(r.area) || /search|browse|discovery|Home|rails|metadata/i.test(r.requirement + r.common + r.platformSpecific));
  if (tab === "playback") return all.filter((r) => /Playback/.test(r.area) || /playback|resume|subtitle|audio|player|buffering|episode/i.test(r.requirement + r.common + r.platformSpecific));
  if (tab === "account") return all.filter((r) => /Account|Entitlements|Login|Commercial/.test(r.area) || /subscription|payment|login|account|profile|entitlement|pairing/i.test(r.requirement + r.common + r.platformSpecific));
  if (tab === "accessibility") return all.filter((r) => /Accessibility|TV UX|Navigation|Layout/.test(r.area) || /focus|keyboard|remote|caption|localization|readable|D-pad/i.test(r.requirement + r.common + r.platformSpecific));
  if (tab === "telemetry") return all.filter((r) => /Telemetry/.test(r.area) || /analytics|health|crash|error|buffering|events/i.test(r.requirement + r.common + r.platformSpecific));
  if (tab === "compliance") return all.filter((r) => /Store|Certification|Commercial|Entitlements|Accessibility/.test(r.area) || /privacy|review|store|certification|policy|support/i.test(r.requirement + r.common + r.platformSpecific));
  return all;
}

const tabTitles: Record<ProductRequirementTab, string> = {
  "product-core": "Product Core",
  discovery: "Discovery",
  playback: "Playback",
  account: "Account & Entitlements",
  accessibility: "Accessibility",
  telemetry: "Analytics & Health",
  compliance: "Store & Certification",
  "qa-matrix": "QA Matrix"
};

export function getOttRequirements(appId = "web-pwa", tab: ProductRequirementTab = "product-core"): OttProductRequirements {
  return {
    appId,
    tab,
    title: tabTitles[tab],
    summary: "Shared OTT core plus platform-native requirements for the selected app version. This is the product requirement matrix, not a generic web-view checklist.",
    rows: rowsForTab(appId, tab)
  };
}

export function getRequirementControlItems(appId: string, tab: ProductRequirementTab) {
  return getOttRequirements(appId, tab).rows.map((row) => ({
    id: row.id,
    label: row.requirement,
    status: row.status === "waiting" ? "not_started" : row.status,
    detail: `${row.common} ${row.platformSpecific}`,
    source: row.status === "not_connected" ? "external_api" : "manual"
  }));
}

export function getRequirementTabs() {
  return [
    { id: "product-core", label: "Product Core" },
    { id: "discovery", label: "Discovery" },
    { id: "playback", label: "Playback" },
    { id: "account", label: "Account & Entitlements" },
    { id: "accessibility", label: "Accessibility" },
    { id: "telemetry", label: "Analytics & Health" },
    { id: "compliance", label: "Store & Certification" },
    { id: "qa-matrix", label: "QA Matrix" }
  ];
}
