const { useEffect, useMemo, useRef, useState } = React;

const Icon = ({ name, className = "h-5 w-5" }) => {
  const icons = {
    home: "M3 11l9-8 9 8M5 10v11h5v-6h4v6h5V10",
    layout: "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z",
    map: "M9 18l-6 3V6l6-3 6 3 6-3v15l-6 3-6-3zM9 3v15M15 6v15",
    tree: "M12 22v-7M8 15h8a4 4 0 0 0 1-7.86 5 5 0 0 0-9.9 0A4 4 0 0 0 8 15z",
    check: "M20 6L9 17l-5-5",
    calendar: "M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z",
    file: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M8 13h8M8 17h5",
    users: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75",
    wrench: "M14.7 6.3a4 4 0 0 0-5 5L3 18l3 3 6.7-6.7a4 4 0 0 0 5-5l-2.3 2.3-3-3z",
    truck: "M3 7h11v9H3zM14 10h4l3 3v3h-7zM7 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM17 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",
    box: "M21 8l-9-5-9 5 9 5 9-5zM3 8v8l9 5 9-5V8M12 13v8",
    bell: "M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M13.73 21a2 2 0 0 1-3.46 0",
    settings: "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1.4 1.67V21a2 2 0 1 1-4 0v-.17A1.7 1.7 0 0 0 8.2 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-1.67-1.4H2.8a2 2 0 1 1 0-4H3A1.7 1.7 0 0 0 4.6 8.2a1.7 1.7 0 0 0-.34-1.88l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 9 4.6 1.7 1.7 0 0 0 10.4 3V2.8a2 2 0 1 1 4 0V3A1.7 1.7 0 0 0 15.8 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9c.2.34.4.67.6 1h.17a2 2 0 1 1 0 4H20a1.7 1.7 0 0 0-.6 1z",
    qr: "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h3v3h-3zM18 18h3v3h-3zM18 14h3M14 21h3M21 14v3",
    download: "M12 3v12M7 10l5 5 5-5M5 21h14",
    camera: "M4 7h3l2-3h6l2 3h3v13H4zM12 17a4 4 0 1 0 0-8 4 4 0 0 0 0 8z",
    money: "M3 6h18v12H3zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM6 9v.01M18 15v.01",
    menu: "M4 6h16M4 12h16M4 18h16",
    x: "M18 6L6 18M6 6l12 12",
    leaf: "M5 21c0-8 5-16 16-18-2 11-10 16-16 18zM9 17c2-4 5-7 10-10",
    upload: "M12 16V4M7 9l5-5 5 5M4 20h16",
    save: "M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2zM17 21v-8H7v8M7 3v5h8",
    assets: "M14.7 6.3a4 4 0 0 0-5 5L4 17l3 3 5.7-5.7a4 4 0 0 0 5-5l-2.3 2.3-3-3zM3 9h8v6H3zM11 12h3l2 2v1h-5M6 18a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM15.5 18a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z",
    news: "M4 5h16v14H4zM8 9h8M8 13h8M8 17h5M4 7H2v10a2 2 0 0 0 2 2",
    building: "M4 21V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v16M9 7h3M9 11h3M9 15h3M3 21h18",
    flow: "M6 4a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM18 16a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM6 8v3a3 3 0 0 0 3 3h6a3 3 0 0 1 3 3v1M9 6h6M15 6l-2-2M15 6l-2 2",
    share: "M4 12v7a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-7M16 6l-4-4-4 4M12 2v14",
    comment: "M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z",
    bag: "M6 7h12l1 14H5L6 7zM9 7a3 3 0 0 1 6 0",
    book: "M4 5a3 3 0 0 1 3-3h13v17H7a3 3 0 0 0-3 3V5zM4 5v17M8 6h8",
    phone: "M22 16.9v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.35 1.9.66 2.79a2 2 0 0 1-.45 2.11L8.1 9.9a16 16 0 0 0 6 6l1.28-1.22a2 2 0 0 1 2.11-.45c.89.31 1.83.53 2.79.66A2 2 0 0 1 22 16.9z",
    globe: "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20zM2 12h20M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20",
    headset: "M4 13v-1a8 8 0 1 1 16 0v1M4 13a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2v-6H4zM20 13h-2v6h2a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2zM18 19a4 4 0 0 1-4 3h-2",
    user: "M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z",
    plus: "M12 5v14M5 12h14",
    edit: "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L8 18l-4 1 1-4z",
    trash: "M3 6h18M8 6V4h8v2M6 6l1 15h10l1-15M10 11v6M14 11v6",
    archive: "M21 8v13H3V8M1 3h22v5H1zM10 12h4",
    history: "M3 12a9 9 0 1 0 3-6.7M3 4v6h6M12 7v5l3 3",
    "cloud-sun": "M12 2v2M4.93 4.93l1.41 1.41M2 12h2M19.07 4.93l-1.41 1.41M18 12h2M8 12a4 4 0 1 1 7.5 2M7 19h10a4 4 0 0 0 0-8 5.5 5.5 0 0 0-10.7 1.4A3.5 3.5 0 0 0 7 19z",
    "calendar-clock": "M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 0 1 2 2v13a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zM12 14v3l2 1",
    more: "M12 8h.01M12 12h.01M12 16h.01",
    shield: "M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",
    restore: "M3 12a9 9 0 1 0 3-6.7M3 4v6h6M12 8v5l4 2",
    refresh: "M21 12a9 9 0 0 1-15.5 6.2M3 12A9 9 0 0 1 18.5 5.8M18 3v4h-4M6 21v-4h4",
  };

  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d={icons[name]} />
    </svg>
  );
};

const navItems = [
  ["Dashboard", "layout", "dashboard"],
  ["Farm Management", "map", "farm-management"],
  ["Tree Management", "tree", "tree-management"],
  ["Daily Report", "file", "daily-report"],
  ["People / HR", "users", "people-hr"],
  ["Inventory / Warehouse", "box", "inventory"],
  ["Equipment & Vehicle", "assets", "equipment"],
  ["Financial", "money", "finance"],
  ["Experiment & R&D", "leaf", "experiment-rd"],
  ["Documents Center", "file", "documents-center"],
  ["Notification Center", "bell", "notification-center"],
  ["Analytics / BI", "layout", "analytics-bi"],
  ["UI Flow Map", "flow", "ui-flow-map"],
  ["Preview Deployment", "share", "preview-deployment"],
  ["User Management", "shield", "user-management"],
  ["Settings", "settings", "settings"],
];

const previewModes = [
  { id: "desktop", label: "คอมพิวเตอร์", icon: "layout", hint: "Sidebar เต็ม / หลายคอลัมน์" },
  { id: "tablet", label: "แท็บเล็ต", icon: "map", hint: "Sidebar ไอคอน / 2 คอลัมน์" },
  { id: "mobile", label: "มือถือ", icon: "menu", hint: "Bottom navigation / 1 คอลัมน์" },
];

const roleOptions = [
  { id: "owner", label: "Owner", th: "เจ้าของ", badge: "bg-goodseed-700 text-white ring-goodseed-700" },
  { id: "partner_owner", label: "Partner Owner", th: "หุ้นส่วนเจ้าของ", badge: "bg-goodseed-700 text-white ring-goodseed-700" },
  { id: "admin", label: "Admin", th: "ผู้ดูแลระบบ", badge: "bg-blue-100 text-blue-700 ring-blue-200" },
  { id: "manager", label: "Farm Manager", th: "ผู้จัดการฟาร์ม", badge: "bg-emerald-100 text-emerald-800 ring-emerald-200" },
  { id: "plot_manager", label: "Plot Manager", th: "ผู้จัดการแปลง", badge: "bg-cyan-100 text-cyan-800 ring-cyan-200" },
  { id: "staff", label: "Staff", th: "พนักงาน", badge: "bg-amber-100 text-amber-800 ring-amber-200" },
  { id: "worker", label: "Worker", th: "คนงาน", badge: "bg-lime-100 text-lime-800 ring-lime-200" },
  { id: "customer", label: "Customer", th: "ลูกค้า", badge: "bg-slate-100 text-slate-700 ring-slate-200" },
  { id: "developer", label: "Developer", th: "นักพัฒนา", badge: "bg-slate-950 text-white ring-slate-950" },
];

const ownerManagedRoleOptions = roleOptions.filter((item) => ["owner", "partner_owner", "admin", "manager", "plot_manager", "staff", "worker"].includes(item.id));

const primaryOwnerEmails = ["tasilanowat1239@gmail.com"];
const supabaseProjectUrl = "https://tobheepbvgtfxxqvuzwx.supabase.co";
const backendRequestKeywords = ["staff", "admin", "manager", "worker", "ผู้จัดการ", "สตาฟ", "พนักงาน", "คนงาน", "หลังบ้าน", "ฟาร์ม", "farm"];

function isPrimaryOwnerEmail(email) {
  return primaryOwnerEmails.includes(String(email || "").trim().toLowerCase());
}

function isOwnerRole(role) {
  return role === "owner" || role === "partner_owner";
}

function getSupabaseConfig() {
  const config = window.GOODSEED_SUPABASE || {};
  const configuredUrl = config.url || window.GOODSEED_SUPABASE_URL || "";
  return {
    url: configuredUrl.startsWith("https://") ? configuredUrl : supabaseProjectUrl,
    anonKey: config.anonKey || window.GOODSEED_SUPABASE_ANON_KEY || "",
  };
}

const goodseedSupabaseLock = async (_name, _acquireTimeout, fn) => fn();

function getSupabaseClient(options = {}) {
  const { silent = false } = options;
  const config = getSupabaseConfig();
  const missingUrl = !config.url || config.url.includes("VITE_SUPABASE_URL");
  const missingKey = !config.anonKey || config.anonKey.includes("VITE_SUPABASE_ANON_KEY") || config.anonKey.includes("your-public-anon-key");
  if (missingUrl || missingKey) {
    if (silent) return null;
    throw new Error("missing-supabase-env");
  }
  if (!window.supabase?.createClient) {
    if (silent) return null;
    throw new Error("missing-supabase-sdk");
  }
  if (!window.goodseedSupabaseClient) {
    window.goodseedSupabaseClient = window.supabase.createClient(config.url, config.anonKey, {
      auth: {
        persistSession: true,
        autoRefreshToken: true,
        detectSessionInUrl: true,
        lock: goodseedSupabaseLock,
      },
    });
  }
  return window.goodseedSupabaseClient;
}

function withSupabaseTimeout(promise, label, ms = 15000) {
  let timeoutId;
  const timeout = new Promise((_, reject) => {
    timeoutId = window.setTimeout(() => reject(new Error(label)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => window.clearTimeout(timeoutId));
}

async function fetchWithTimeout(url, options = {}, timeoutMs = 15000, timeoutLabel = "request-timeout") {
  const controller = new AbortController();
  const timeoutId = window.setTimeout(() => controller.abort(new Error(timeoutLabel)), timeoutMs);
  try {
    return await fetch(url, { ...options, signal: controller.signal });
  } catch (error) {
    if (error?.name === "AbortError" || error?.message === timeoutLabel) {
      throw new Error(timeoutLabel);
    }
    throw error;
  } finally {
    window.clearTimeout(timeoutId);
  }
}

function getSupabaseStorageKey() {
  const config = getSupabaseConfig();
  try {
    const projectRef = new URL(config.url).hostname.split(".")[0];
    return `sb-${projectRef}-auth-token`;
  } catch (error) {
    return "sb-goodseed-auth-token";
  }
}

function persistSupabaseSession(session) {
  if (!session?.access_token || !session?.refresh_token) return;
  try {
    const expiresAt = session.expires_at || Math.floor(Date.now() / 1000) + Number(session.expires_in || 3600);
    localStorage.setItem(getSupabaseStorageKey(), JSON.stringify({ ...session, expires_at: expiresAt }));
  } catch (error) {
    console.warn("GoodSeed auth session storage failed", error);
  }
}

function getPersistedSupabaseSession() {
  try {
    const raw = localStorage.getItem(getSupabaseStorageKey());
    return raw ? JSON.parse(raw) : null;
  } catch (error) {
    return null;
  }
}

function decodeJwtPayload(token) {
  try {
    const payload = String(token || "").split(".")[1];
    if (!payload) return null;
    const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
    const padded = `${normalized}${"=".repeat((4 - normalized.length % 4) % 4)}`;
    return JSON.parse(atob(padded));
  } catch (error) {
    return null;
  }
}

function clearSupabaseAuthStorage() {
  try {
    Object.keys(localStorage)
      .filter((key) => key.startsWith("sb-") || key.includes("supabase.auth.token"))
      .forEach((key) => localStorage.removeItem(key));
  } catch (error) {
    // Some browsers can block localStorage in strict privacy contexts.
  }
}

function normalizeAuthRole(value) {
  const normalized = String(value || "").trim().toLowerCase().replace(/\s+/g, "-").replace("/", "-");
  const roleAliases = {
    owner: "owner",
    "partner-owner": "partner_owner",
    partner_owner: "partner_owner",
    coowner: "partner_owner",
    "co-owner": "partner_owner",
    admin: "admin",
    administrator: "admin",
    manager: "manager",
    "farm-manager": "manager",
    farm_manager: "manager",
    "plot-manager": "plot_manager",
    plot_manager: "plot_manager",
    supervisor: "plot_manager",
    "admin-manager": "manager",
    staff: "staff",
    worker: "worker",
    customer: "customer",
  };
  return roleAliases[normalized] || null;
}

function resolveSupabaseRole(user) {
  const email = user?.email?.trim().toLowerCase();
  if (isPrimaryOwnerEmail(email)) return "owner";
  const metadata = { ...(user?.user_metadata || {}), ...(user?.app_metadata || {}) };
  const approvedStatus = String(metadata.approval_status || metadata.status || "approved").toLowerCase();
  const assignedRole = normalizeAuthRole(metadata.goodseed_role || metadata.role || metadata.account_role || metadata.accountType) || "customer";
  if (assignedRole !== "customer" && !["approved", "active"].includes(approvedStatus)) return "customer";
  return assignedRole;
}

function buildSupabaseProfile(user, data = {}) {
  const email = user?.email?.trim().toLowerCase() || "";
  const metadata = user?.user_metadata || {};
  const isPrimaryOwner = isPrimaryOwnerEmail(email);
  const hasProfileRow = Boolean(data?.id);
  const requestedRole = normalizeAuthRole(data?.requested_role || metadata.requested_role) || "worker";
  const role = isPrimaryOwner ? "owner" : normalizeAuthRole(data?.role || metadata.role) || (hasProfileRow ? "customer" : requestedRole);
  const approvalStatus = isPrimaryOwner ? "approved" : (data?.approval_status || metadata.approval_status || (hasProfileRow && role === "customer" ? "approved" : "pending"));
  return {
    id: user.id,
    email,
    fullName: data?.full_name || metadata.full_name || email,
    phone: data?.phone || metadata.phone || "",
    role,
    requestedRole,
    approvalStatus,
    requestNote: data?.request_note || metadata.request_note || "",
    requestedAt: data?.requested_at || metadata.requested_at || "",
    ownerResponse: data?.owner_response || metadata.owner_response || "",
    disabled: Boolean(data?.disabled),
  };
}

function signupApprovalStatus(requestedRole, email) {
  if (isPrimaryOwnerEmail(email)) return "approved";
  return requestedRole === "customer" ? "approved" : "pending";
}

function isPendingApprovalStatus(status) {
  return ["pending", "pending-approval", "pending-review"].includes(String(status || "").toLowerCase());
}

function isMissingOptionalProfileColumn(error) {
  const message = String(error?.message || error || "").toLowerCase();
  return message.includes("owner_response") || message.includes("requested_at") || message.includes("username");
}

function profileDisplayName(profile) {
  const rawName = String(profile?.fullName || "").trim();
  if (rawName && rawName !== profile?.email) return rawName;
  const email = String(profile?.email || "").trim();
  return email ? email.split("@")[0] : "GOODSEED User";
}

function canUseBackendPresence(role) {
  return ["owner", "partner_owner", "admin", "manager", "plot_manager", "staff", "worker", "developer"].includes(role);
}

function normalizePresenceRow(row) {
  return {
    id: row.user_id || row.id,
    name: row.full_name || row.email || "GOODSEED User",
    email: row.email || "",
    role: roleInfo(row.role || "staff").label,
    activity: row.current_page ? `กำลังใช้งาน ${row.current_page}` : "ออนไลน์ในระบบ",
    page: row.current_page || "",
    lastSeen: row.last_seen_at || row.updated_at || row.created_at,
  };
}

function activePresenceCutoff(minutes = 2) {
  return new Date(Date.now() - minutes * 60 * 1000).toISOString();
}

async function supabaseFetch(path, { accessToken, method = "GET", body, timeoutMs = 15000, timeoutLabel = "supabase-request-timeout" } = {}) {
  const config = getSupabaseConfig();
  if (!config.url || !config.anonKey) throw new Error("missing-supabase-env");
  const response = await fetchWithTimeout(`${config.url}${path}`, {
    method,
    headers: {
      apikey: config.anonKey,
      Authorization: `Bearer ${accessToken || config.anonKey}`,
      "Content-Type": "application/json",
      ...(method !== "GET" ? { Prefer: "return=representation,resolution=merge-duplicates" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  }, timeoutMs, timeoutLabel);
  const text = await response.text();
  let payload = null;
  try {
    payload = text ? JSON.parse(text) : null;
  } catch (error) {
    payload = { message: text };
  }
  if (!response.ok) {
    throw new Error(payload?.msg || payload?.message || payload?.error_description || payload?.error || `Supabase request failed (${response.status})`);
  }
  return payload;
}

async function goodseedAdminUsersRequest(action, payload = {}, accessToken = "") {
  const response = await fetchWithTimeout("/api/admin-users", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
    },
    body: JSON.stringify({ action, ...payload }),
  }, 7000, "admin-users-timeout");
  const data = await response.json().catch(() => null);
  if (!response.ok) {
    throw new Error(data?.message || data?.error || `Admin users request failed (${response.status})`);
  }
  return data;
}

async function resolveLoginIdentifier(identifier) {
  const normalized = String(identifier || "").trim().toLowerCase();
  if (!normalized || normalized.includes("@")) return normalized;
  try {
    const result = await goodseedAdminUsersRequest("resolveLogin", { username: normalized });
    return result.email || normalized;
  } catch (error) {
    const message = String(error?.message || "").toLowerCase();
    if (
      message.includes("missing supabase_service_role_key")
      || message.includes("admin-users-timeout")
      || message.includes("failed to fetch")
    ) {
      throw new Error("username-login-unavailable");
    }
    throw error;
  }
}

async function signInWithPasswordDirect(email, password) {
  const session = await supabaseFetch("/auth/v1/token?grant_type=password", {
    method: "POST",
    body: { email, password },
    timeoutMs: 15000,
    timeoutLabel: "login-timeout",
  });
  if (!session?.access_token || !session?.refresh_token || !session?.user) {
    throw new Error("Supabase login did not return a valid session");
  }
  persistSupabaseSession(session);
  const client = getSupabaseClient({ silent: true });
  if (client?.auth?.setSession) {
    client.auth
      .setSession({
        access_token: session.access_token,
        refresh_token: session.refresh_token,
      })
      .catch((error) => {
        console.warn("GoodSeed Supabase SDK session sync failed; continuing with stored session", error);
      });
  }
  return { data: { session, user: session.user }, error: null };
}

async function signUpWithPasswordDirect({ email, password, fullName, phone, requestedRole, requestNote }) {
  const normalizedEmail = String(email || "").trim().toLowerCase();
  const normalizedRole = normalizeAuthRole(requestedRole) || "worker";
  const approvalStatus = signupApprovalStatus(normalizedRole, normalizedEmail);
  const client = getSupabaseClient();
  const { data, error } = await withSupabaseTimeout(
    client.auth.signUp({
      email: normalizedEmail,
      password,
      options: {
        data: {
          full_name: String(fullName || "").trim(),
          phone: String(phone || "").trim(),
          role: normalizedRole,
          goodseed_role: normalizedRole,
          requested_role: normalizedRole,
          approval_status: approvalStatus,
          request_note: String(requestNote || "").trim(),
          requested_at: new Date().toISOString(),
        },
      },
    }),
    "signup-timeout"
  );
  if (error) return { data, error };
  if (data?.session) persistSupabaseSession(data.session);
  try {
    await goodseedAdminUsersRequest("registerRequest", {
      email: normalizedEmail,
      fullName,
      phone,
      requestedRole: normalizedRole,
      requestNote,
    });
  } catch (requestError) {
    console.warn("GoodSeed pending profile registration failed", requestError);
  }
  return { data, error: null };
}

async function loadSupabaseProfileDirect(user, accessToken) {
  const id = encodeURIComponent(user.id);
  let rows;
  try {
    rows = await supabaseFetch(`/rest/v1/profiles?select=id,email,full_name,phone,role,requested_role,approval_status,request_note,requested_at,owner_response,disabled&id=eq.${id}`, { accessToken });
  } catch (error) {
    if (!isMissingOptionalProfileColumn(error)) throw error;
    rows = await supabaseFetch(`/rest/v1/profiles?select=id,email,full_name,phone,role,requested_role,approval_status,request_note,disabled&id=eq.${id}`, { accessToken });
  }
  const data = Array.isArray(rows) ? rows[0] : null;
  const profile = buildSupabaseProfile(user, data);
  if (isPrimaryOwnerEmail(profile.email) && (!data || data.role !== "owner" || data.approval_status !== "approved")) {
    await supabaseFetch("/rest/v1/profiles?on_conflict=id", {
      accessToken,
      method: "POST",
      body: {
        id: user.id,
        email: profile.email,
        full_name: profile.fullName,
        role: "owner",
        requested_role: "owner",
        approval_status: "approved",
        disabled: false,
      },
    });
  }
  return profile;
}

async function loadSupabaseProfile(user) {
  const client = getSupabaseClient();
  const email = user?.email?.trim().toLowerCase() || "";
  const isPrimaryOwner = isPrimaryOwnerEmail(email);
  let { data, error } = await client
    .from("profiles")
    .select("id,email,full_name,phone,role,requested_role,approval_status,request_note,requested_at,owner_response,disabled")
    .eq("id", user.id)
    .maybeSingle();
  if (isMissingOptionalProfileColumn(error)) {
    const fallback = await client
      .from("profiles")
      .select("id,email,full_name,phone,role,requested_role,approval_status,request_note,disabled")
      .eq("id", user.id)
      .maybeSingle();
    data = fallback.data;
    error = fallback.error;
  }
  if (error) {
    console.warn("GoodSeed profile lookup failed", error);
  }
  const profile = buildSupabaseProfile(user, data);
  if (isPrimaryOwner && (!data || data.role !== "owner" || data.approval_status !== "approved")) {
    const { error: upsertError } = await client.from("profiles").upsert({
      id: user.id,
      email,
      full_name: profile.fullName,
      role: "owner",
      requested_role: "owner",
      approval_status: "approved",
      disabled: false,
    }, { onConflict: "id" });
    if (upsertError) {
      console.warn("GoodSeed owner profile sync failed", upsertError);
    }
  }
  return profile;
}

function canEnterBackend(profile) {
  if (!profile || profile.disabled) return false;
  if (profile.approvalStatus === "rejected" || profile.approvalStatus === "disabled") return false;
  if (profile.role === "customer") return false;
  return ["approved", "active"].includes(String(profile.approvalStatus || "").toLowerCase());
}

function backendAccessBlockMessage(profile) {
  const ownerResponse = String(profile?.ownerResponse || "").trim();
  const responseText = ownerResponse ? `\n\nข้อความจาก Owner: ${ownerResponse}` : "";
  if (!profile) return "ไม่พบบัญชีผู้ใช้ กรุณาลองเข้าสู่ระบบอีกครั้ง / Account profile was not found.";
  if (profile.disabled) return `บัญชีนี้ถูกปิดการใช้งาน กรุณาติดต่อ Owner / This account is disabled.${responseText}`;
  if (profile.approvalStatus === "rejected") return `คำขอใช้บัญชีนี้ถูกปฏิเสธ กรุณาติดต่อ Owner / This account was rejected.${responseText}`;
  if (profile.role === "customer") return "บัญชี Customer ใช้งานได้เฉพาะหน้าเว็บไซต์และข้อมูลที่เปิดเผย ไม่สามารถเข้า Backend ได้ / Customer accounts cannot access Backend.";
  if (isPendingApprovalStatus(profile.approvalStatus)) {
    return `บัญชี ${roleInfo(profile.requestedRole || profile.role).label} ต้องรอ Owner อนุมัติก่อนเข้า Backend / This account is waiting for Owner approval.${responseText}`;
  }
  return `บัญชีนี้ยังไม่มีสิทธิ์เข้า Backend กรุณาติดต่อ Owner / This account is not allowed to access Backend.${responseText}`;
}

function resetViewportScroll() {
  window.scrollTo({ top: 0, left: 0, behavior: "auto" });
  if (document.scrollingElement) {
    document.scrollingElement.scrollLeft = 0;
  }
  document.documentElement.scrollLeft = 0;
  document.body.scrollLeft = 0;
}

function AppCrashFallback({ error }) {
  const message = error?.message || "Unknown application error";
  return (
    <div className="grid min-h-screen place-items-center bg-goodseed-50 px-4 py-10">
      <div className="w-full max-w-xl rounded-2xl border border-red-100 bg-white p-6 text-center shadow-soft">
        <img src={farmLogo} alt="GoodSeed Farm" className="mx-auto h-16 w-16 rounded-2xl object-cover" />
        <h1 className="mt-4 text-2xl font-black text-goodseed-950">ระบบโหลดไม่สำเร็จ</h1>
        <p className="mt-2 text-sm font-semibold leading-6 text-goodseed-700">หน้าเว็บเจอข้อผิดพลาดชั่วคราว กรุณากลับไปหน้า Login แล้วเข้าสู่ระบบใหม่อีกครั้ง</p>
        <p className="mt-3 rounded-lg bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{message}</p>
        <div className="mt-5 grid gap-3 sm:grid-cols-2">
          <button type="button" onClick={() => window.location.href = "./index.html#login"} className="rounded-xl bg-goodseed-700 px-4 py-3 text-sm font-extrabold text-white">กลับหน้า Login</button>
          <button type="button" onClick={() => window.location.reload()} className="rounded-xl border border-goodseed-200 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800">Reload</button>
        </div>
      </div>
    </div>
  );
}

class AppErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    console.error("GoodSeed app crashed", error, info);
  }

  render() {
    if (this.state.error) return <AppCrashFallback error={this.state.error} />;
    return this.props.children;
  }
}

function supabaseAuthMessage(error) {
  const rawMessage = String(error?.message || error || "");
  const normalizedMessage = rawMessage.toLowerCase();
  if (error?.message === "missing-supabase-env") {
    return "ยังไม่ได้ตั้งค่า VITE_SUPABASE_ANON_KEY กรุณาเพิ่มค่าใน .env หรือ Vercel Environment Variables ก่อนใช้งาน Supabase Login";
  }
  if (error?.message === "missing-supabase-sdk") {
    return "โหลด Supabase SDK ไม่สำเร็จ กรุณาตรวจสอบอินเทอร์เน็ตหรือ CDN";
  }
  if (error?.message === "username-login-unavailable") {
    return "ระบบ Login ด้วย Username ยังไม่ได้ตั้งค่า SUPABASE_SERVICE_ROLE_KEY บน Vercel กรุณาใช้ Email เข้าสู่ระบบก่อน หรือเพิ่ม Environment Variable นี้แล้ว Deploy ใหม่";
  }
  if (error?.message === "login-timeout") {
    return "เชื่อมต่อ Supabase Login นานเกินไป กรุณาตรวจสอบอินเทอร์เน็ตแล้วลองใหม่อีกครั้ง หรือเข้าสู่ระบบด้วย Email";
  }
  if (error?.message === "profile-timeout") {
    return "เข้าสู่ระบบได้แล้ว แต่โหลดข้อมูล Role/Profile นานเกินไป กรุณากด Reload แล้วลองใหม่";
  }
  if (normalizedMessage.includes("email not confirmed") || normalizedMessage.includes("confirm your email")) {
    return "กรุณายืนยันอีเมลก่อนเข้าสู่ระบบ / Please confirm your email before signing in.";
  }
  return rawMessage || "เกิดข้อผิดพลาดในการเชื่อมต่อ Supabase";
}

function wantsBackendAccess(note = "") {
  const normalized = note.toLowerCase();
  return backendRequestKeywords.some((keyword) => normalized.includes(keyword));
}

function accountStatusTone(status) {
  if (status === "approved" || status === "active") return "bg-goodseed-100 text-goodseed-800 ring-goodseed-200";
  if (isPendingApprovalStatus(status)) return "bg-amber-100 text-amber-800 ring-amber-200";
  if (status === "rejected" || status === "disabled") return "bg-red-100 text-red-700 ring-red-200";
  return "bg-slate-100 text-slate-700 ring-slate-200";
}

const appLocales = {
  th: {
    publicNav: {
      "public-home": "หน้าแรก",
      "public-about": "เกี่ยวกับเรา",
      "public-farm": "ฟาร์มของเรา",
      "public-products": "สินค้า",
      "public-technology": "Smart Farm & Technology",
      "public-esg": "ความยั่งยืน / ESG",
      "public-news": "ข่าวสารและกิจกรรม",
      "public-gallery": "แกลเลอรี / สื่อ",
      "public-company-profile": "Company Profile",
      "public-contact": "ติดต่อเรา",
    },
    internalNav: {
      dashboard: "หน้าหลัก",
      "work-planning": "แผนงานฟาร์ม / KPI",
      "farm-calendar": "ปฏิทินงานฟาร์ม",
      "farm-kpi": "ประเมิน KPI ฟาร์ม",
      "farm-management": "จัดการฟาร์ม",
      "tree-management": "จัดการต้นไม้",
      "daily-report": "รายงานประจำวัน",
      "people-hr": "บุคลากร / HR",
      inventory: "คลังวัสดุ",
      equipment: "อุปกรณ์และรถยนต์",
      finance: "การเงิน",
      "experiment-rd": "งานทดลอง / R&D",
      "documents-center": "ศูนย์เอกสาร",
      "notification-center": "ศูนย์แจ้งเตือน",
      "analytics-bi": "วิเคราะห์ข้อมูล / BI",
      "ui-flow-map": "UI Flow Map",
      "preview-deployment": "Preview Deployment",
      "user-management": "จัดการผู้ใช้งาน",
      settings: "ตั้งค่าระบบ",
    },
    actions: {
      contact: "ติดต่อเรา",
      login: "เข้าสู่ระบบ",
      publicWebsite: "เว็บไซต์บริษัท",
      openGoogleMaps: "เปิดใน Google Maps",
      directionsToFarm: "นำทางมาฟาร์ม",
      directions: "นำทาง",
      openMapsEn: "Open Google Maps",
      sendMessage: "ส่งข้อความ",
      viewProducts: "ดูสินค้า",
      companyProfile: "Company Profile",
      forgotPassword: "Forgot Password?",
      backToWebsite: "กลับหน้าเว็บไซต์บริษัท",
    },
    login: {
      title: "เข้าสู่ระบบ GOODSEED Farm",
      subtitle: "ระบบจะตรวจสอบสิทธิ์และแสดงเมนูตาม Role ของบัญชีหลัง Login",
      email: "Email / Username",
      password: "Password",
      roleAssigned: "Role is assigned by account",
      emptyError: "กรุณากรอก Email / Username และ Password",
      internalLabel: "Internal Management System",
      operationCenter: "Smart Farm Operation Center",
      operationText: "ระบบงานภายในสำหรับบริหารฟาร์ม รายงานผล ตรวจสอบงาน วิเคราะห์ข้อมูล KPI บุคลากร ต้นทุน และ Real-time Monitoring",
    },
    topbar: {
      searchPlaceholder: "ค้นหาแปลง, ต้นไม้, งาน, คนงาน...",
      date: "วันที่ปัจจุบัน",
      weekday: "วันปัจจุบัน",
      loggedInAs: "Logged in as",
      systemTitle: "GoodSeed Farm Management System",
    },
    preview: { desktop: "คอมพิวเตอร์", tablet: "แท็บเล็ต", mobile: "มือถือ" },
    system: { status: "สถานะระบบ", sync: "Real-time mock sync 14:32 น." },
    publicHome: {
      label: "Smart Agriculture & Nursery Farm",
      heading: "GOODSEED FARM",
      subheading: "ฟาร์มไม้ล้อมและเกษตรผสมผสานสมัยใหม่ เพื่อการเติบโตอย่างยั่งยืน เชื่อมโยงการเกษตรคุณภาพ มาตรฐานการผลิต และอนาคตของตลาดส่งออก",
      description: "พัฒนาระบบฟาร์มสมัยใหม่ที่ผสานเทคโนโลยี การจัดการข้อมูล และการเกษตรยั่งยืน เพื่อสร้างมาตรฐานใหม่ของอุตสาหกรรมไม้ล้อมไทย",
      scroll: "เลื่อนดูเพิ่มเติม",
      stats: {
        farmArea: { label: "พื้นที่พัฒนาฟาร์ม", detail: "ไม้ล้อมและเกษตรผสมผสาน" },
        currentTrees: { label: "ต้นไม้ปัจจุบัน", detail: "รอบปลูก A-C" },
        expansionGoal: { label: "เป้าหมายหลังขยาย", detail: "รอบปลูก A-F" },
        traceability: { label: "ระบบตรวจสอบ", detail: "Traceability ทุกแปลง" },
      },
    },
    contact: {
      eyebrow: "Contact Us",
      title: "ติดต่อ GOODSEED Farm",
      subtitle: "โคกแสมสาร, โคกเจริญ, ลพบุรี พร้อมช่องทางสำหรับลูกค้า คู่ค้า นักลงทุน และผู้สนใจเยี่ยมชมฟาร์ม",
      mapBadge: "Map & Directions",
      mapTitle: "เดินทางมาที่ GOODSEED Farm",
      mapSubtitle: "ดูแผนที่ เส้นทาง และกดนำทางมายังฟาร์มได้ผ่าน Google Maps",
      contactInformation: "Contact Information",
      address: "ตำบลโคกแสมสาร อำเภอโคกเจริญ จังหวัดลพบุรี",
      businessHours: "จันทร์ - เสาร์ 08:00 - 17:00 น.",
      locationTitle: "GOODSEED Farm Location",
      locationText: "กดปุ่มด้านล่างเพื่อเปิดเส้นทางใน Google Maps",
      visitTitle: "นัดหมายเยี่ยมชมฟาร์ม",
      visitText: "สามารถติดต่อเพื่อนัดหมายล่วงหน้าสำหรับการเยี่ยมชมแปลงไม้ล้อม พื้นที่ทดลอง ระบบน้ำ และ Company Profile ของ GOODSEED Farm",
      name: "ชื่อผู้ติดต่อ",
      company: "บริษัท / หน่วยงาน",
      email: "อีเมล",
      phone: "เบอร์โทร",
      message: "ข้อความ",
    },
  },
  en: {
    publicNav: {
      "public-home": "Home",
      "public-about": "About Us",
      "public-farm": "Our Farm",
      "public-products": "Products",
      "public-technology": "Smart Farm & Technology",
      "public-esg": "Sustainability / ESG",
      "public-news": "News & Activities",
      "public-gallery": "Gallery / Media",
      "public-company-profile": "Company Profile",
      "public-contact": "Contact Us",
    },
    internalNav: {
      dashboard: "Dashboard",
      "work-planning": "Farm Work Planning / KPI",
      "farm-calendar": "Farm Calendar",
      "farm-kpi": "Farm KPI",
      "farm-management": "Farm Management",
      "tree-management": "Tree Management",
      "daily-report": "Daily Report",
      "people-hr": "People / HR",
      inventory: "Inventory / Warehouse",
      equipment: "Equipment & Vehicle",
      finance: "Financial",
      "experiment-rd": "Experiment & R&D",
      "documents-center": "Documents Center",
      "notification-center": "Notification Center",
      "analytics-bi": "Analytics / BI",
      "ui-flow-map": "UI Flow Map",
      "preview-deployment": "Preview Deployment",
      "user-management": "User Management",
      settings: "Settings",
    },
    actions: {
      contact: "Contact Us",
      login: "Login",
      publicWebsite: "Public Website",
      openGoogleMaps: "Open in Google Maps",
      directionsToFarm: "Get Directions",
      directions: "Directions",
      openMapsEn: "Open Google Maps",
      sendMessage: "Send Message",
      viewProducts: "View Products",
      companyProfile: "Company Profile",
      forgotPassword: "Forgot Password?",
      backToWebsite: "Back to Company Website",
    },
    login: {
      title: "Login to GOODSEED Farm",
      subtitle: "The system checks your account role and shows the correct menu after login.",
      email: "Email / Username",
      password: "Password",
      roleAssigned: "Role is assigned by account",
      emptyError: "Please enter Email / Username and Password.",
      internalLabel: "Internal Management System",
      operationCenter: "Smart Farm Operation Center",
      operationText: "Internal operations for farm management, reporting, work inspection, KPI analytics, workforce, cost control and real-time monitoring.",
    },
    topbar: {
      searchPlaceholder: "Search plots, trees, tasks, workers...",
      date: "Current date",
      weekday: "Current weekday",
      loggedInAs: "Logged in as",
      systemTitle: "GoodSeed Farm Management System",
    },
    preview: { desktop: "Desktop", tablet: "Tablet", mobile: "Mobile" },
    system: { status: "System Status", sync: "Real-time mock sync 14:32" },
    publicHome: {
      label: "Smart Agriculture & Nursery Farm",
      heading: "GOODSEED FARM",
      subheading: "A modern nursery and integrated agriculture farm for sustainable growth and future export markets.",
      description: "We combine smart farm technology, data-driven operations and sustainable agriculture to build a new standard for Thailand's landscape tree industry.",
      scroll: "Scroll to explore",
      stats: {
        farmArea: { label: "Farm Development Area", detail: "Landscape trees and integrated agriculture" },
        currentTrees: { label: "Current Trees", detail: "Planting rounds A-C" },
        expansionGoal: { label: "Expansion Goal", detail: "Planting rounds A-F" },
        traceability: { label: "Traceability System", detail: "QR tracking for every plot" },
      },
    },
    contact: {
      eyebrow: "Contact Us",
      title: "Contact GOODSEED Farm",
      subtitle: "Khok Samran, Khok Charoen, Lopburi. For customers, partners, investors and farm visits.",
      mapBadge: "Map & Directions",
      mapTitle: "Visit GOODSEED Farm",
      mapSubtitle: "View the map, route and open directions to the farm with Google Maps.",
      contactInformation: "Contact Information",
      address: "Khok Samran, Khok Charoen District, Lopburi, Thailand",
      businessHours: "Monday - Saturday, 08:00 - 17:00",
      locationTitle: "GOODSEED Farm Location",
      locationText: "Use the button below to open directions in Google Maps.",
      visitTitle: "Schedule a Farm Visit",
      visitText: "Contact us in advance to visit our landscape tree plots, R&D area, water system and GOODSEED Farm company profile.",
      name: "Contact Name",
      company: "Company / Organization",
      email: "Email",
      phone: "Phone",
      message: "Message",
    },
  },
};

function translatePath(language, key) {
  return key.split(".").reduce((current, part) => current?.[part], appLocales[language]) ??
    key.split(".").reduce((current, part) => current?.[part], appLocales.th);
}

function formatBangkokDate(language = "th", options = {}) {
  const locale = language === "en" ? "en-US" : "th-TH-u-ca-buddhist";
  return new Intl.DateTimeFormat(locale, { timeZone: "Asia/Bangkok", ...options }).format(new Date());
}

function formatTopbarDate(language = "th") {
  return formatBangkokDate(language, { day: "numeric", month: "long", year: "numeric" });
}

function formatTopbarWeekday(language = "th") {
  return formatBangkokDate(language, { weekday: "long" });
}

function getStoredLanguage() {
  try {
    return localStorage.getItem("goodseed-language") || "th";
  } catch (error) {
    return "th";
  }
}

function LanguageToggle({ language, setLanguage, compact = false }) {
  const options = [
    { id: "th", label: compact ? "TH" : "🇹🇭 ไทย" },
    { id: "en", label: compact ? "EN" : "🇬🇧 English" },
  ];
  return (
    <div className="inline-flex items-center rounded-xl border border-goodseed-100 bg-white p-1 shadow-sm">
      {options.map((option) => (
        <button
          key={option.id}
          type="button"
          onClick={() => setLanguage(option.id)}
          className={`min-h-9 rounded-lg px-3 text-xs font-extrabold transition ${language === option.id ? "bg-goodseed-700 text-white shadow-sm" : "text-goodseed-800 hover:bg-goodseed-50"}`}
        >
          {option.label}
        </button>
      ))}
    </div>
  );
}

const pagePermissions = {
  dashboard: ["owner", "admin", "manager", "plot_manager", "staff", "worker"],
  "work-planning": ["owner", "admin", "manager", "plot_manager", "staff"],
  "farm-calendar": ["owner", "admin", "manager", "plot_manager", "staff"],
  "farm-kpi": ["owner", "admin", "manager", "plot_manager", "staff"],
  "farm-management": ["owner", "admin", "manager", "plot_manager", "staff"],
  "tree-management": ["owner", "admin", "manager", "plot_manager", "staff"],
  "daily-report": ["owner", "admin", "manager", "plot_manager", "staff", "worker"],
  "people-hr": ["owner", "admin", "manager", "staff"],
  inventory: ["owner", "admin", "manager", "plot_manager", "staff"],
  equipment: ["owner", "admin", "manager", "plot_manager", "staff"],
  finance: ["owner", "admin", "manager", "staff"],
  "experiment-rd": ["owner", "admin", "manager", "plot_manager", "staff"],
  "documents-center": ["owner", "admin", "manager", "plot_manager", "staff"],
  "notification-center": ["owner", "admin", "manager", "plot_manager", "staff", "worker"],
  "analytics-bi": ["owner", "admin", "manager", "plot_manager", "staff"],
  "ui-flow-map": ["owner", "admin", "developer"],
  "preview-deployment": ["owner", "admin", "developer"],
  "user-management": ["owner"],
  settings: ["owner"],
  "organization-goals": ["owner", "admin", "manager", "plot_manager", "staff"],
  "news-promotion": ["owner", "admin", "manager", "staff"],
  "company-profile": ["owner", "admin", "manager", "staff"],
  plots: ["owner", "admin", "manager", "plot_manager", "staff"],
  trees: ["owner", "admin", "manager", "plot_manager", "staff"],
  "daily-work": ["owner", "admin", "manager", "plot_manager", "staff", "worker"],
  responsibility: ["owner", "admin", "manager", "plot_manager", "staff", "worker"],
  "report-form": ["owner", "admin", "manager", "plot_manager", "staff", "worker"],
  workers: ["owner", "admin", "manager", "plot_manager", "staff"],
  stock: ["owner", "admin", "manager", "plot_manager", "staff"],
  alerts: ["owner", "admin", "manager", "plot_manager", "staff"],
  "owner-review": ["owner", "admin", "manager"],
};

const permissionOverridesStorageKey = "goodseed-permission-overrides";

function readPermissionOverrides() {
  try {
    return JSON.parse(localStorage.getItem(permissionOverridesStorageKey) || "{}");
  } catch (error) {
    return {};
  }
}

function writePermissionOverrides(overrides) {
  try {
    localStorage.setItem(permissionOverridesStorageKey, JSON.stringify(overrides));
  } catch (error) {
    // Permission storage can be unavailable in privacy-restricted contexts.
  }
}

function effectivePermissions(pageId, overrides = readPermissionOverrides()) {
  const base = pagePermissions[pageId] || ["owner"];
  const custom = Array.isArray(overrides[pageId]) ? overrides[pageId] : base;
  return Array.from(new Set(["owner", "partner_owner", ...custom]));
}

function roleInfo(role) {
  return roleOptions.find((item) => item.id === role) || roleOptions[0];
}

function canAccess(role, pageId) {
  if (isOwnerRole(role)) return true;
  return effectivePermissions(pageId).includes(role);
}

function visibleNavItems(role) {
  return navItems.filter(([, , id]) => canAccess(role, id));
}

const initialTasks = [
  { id: 1, owner: "คุณหวาน", role: "ผู้จัดการแปลง", duty: "ตรวจแปลง A1 และสรุปรายงานภาพรวม", area: "แปลง A1", frequency: "ทุกวัน", status: "กำลังทำ", image: "มีรูป 6 ภาพ", note: "พบใบเหลือง 8 ต้น" },
  { id: 2, owner: "คุณหวาน", role: "ผู้จัดการแปลง", duty: "ตรวจระบบน้ำและอนุมัติการเบิกวัสดุ", area: "แปลง A2", frequency: "รายสัปดาห์", status: "เสร็จแล้ว", image: "มีรูปวาล์วน้ำ", note: "แรงดันน้ำปกติ" },
  { id: 3, owner: "คุณหวาน", role: "ผู้จัดการแปลง", duty: "ติดตามผลทดลองปุ๋ย GS-03", area: "แปลงทดลอง B1", frequency: "รายเดือน", status: "มีปัญหา", image: "มีรูป 3 ภาพ", note: "รอเจ้าของอนุมัติสูตรต่อไป" },
  { id: 4, owner: "พี่ไกร", role: "คนงานฟาร์ม", duty: "รดน้ำและตรวจหัวน้ำหยด", area: "แปลง A1", frequency: "ทุกวัน", status: "รอดำเนินการ", image: "รออัปโหลด", note: "เริ่มรอบเย็น 16:00 น." },
  { id: 5, owner: "พี่สมชาย", role: "คนงานฟาร์ม", duty: "ถอนหญ้าและเก็บเศษวัชพืช", area: "แปลง A2", frequency: "รายสัปดาห์", status: "กำลังทำ", image: "มีรูปก่อนทำ", note: "เสร็จแล้ว 60%" },
  { id: 6, owner: "พี่ไกร", role: "คนงานฟาร์ม", duty: "ใส่ปุ๋ยและตรวจโรคแมลง", area: "แปลง B1", frequency: "รายฤดูกาล", status: "เสร็จแล้ว", image: "มีรูปหลังทำ", note: "ไม่พบแมลงเพิ่ม" },
];

const initialReports = [
  { id: 1, date: "2026-05-24", reporter: "คุณหวาน", weather: "แดดจัด มีลมอ่อน", area: "แปลง A1", work: "รดน้ำ, ตรวจระบบน้ำ, ตรวจโรคแมลง", issue: "พบเพลี้ยอ่อน 2 จุด", normal: 1232, abnormal: 18, water: "ให้น้ำครบทุกโซน", fertilizer: "ใส่ปุ๋ย GS-03 เสร็จ 78%", disease: "เพลี้ยอ่อนเล็กน้อย", experiment: "ต้นไม้กลุ่มทดลองโตเฉลี่ย +8.4%", summary: "แปลง A1 โดยรวมปกติ ต้องติดตามเพลี้ยอ่อน", photos: "ภาพแปลง 8 รูป", summaryPhoto: "ภาพสรุป 2 รูป", workType: "Tree Inspection", workStatus: "Done", plotId: "A1", rowId: "B17", rowsInspected: 36, treesPlanted: 220, laborCount: 5, hoursWorked: 8, materialUsed: "ปุ๋ย GS-03", materialQty: 12, dailyCost: 6800, progressPercent: 88, growthRate: 8.4, survivalRate: 98.6, photoEvidence: "ภาพงาน 6 รูป", soilCondition: "ดินชื้น", standingWater: "ไม่มีน้ำขัง", fieldWeatherNote: "แดดแรงช่วงบ่าย ควรตรวจความชื้นก่อนรดน้ำรอบเย็น", weatherPhoto: "ภาพสภาพดิน 2 รูป", qrType: "QR ต้นไม้", treeId: "TREE-A1-00482", plotZone: "A1 / Zone 1", treeSpecies: "จามจุรีทอง", treeStatus: "ต้องติดตาม", qrIssue: "พบเพลี้ยอ่อนและใบเหลือง", qrPhoto: "ภาพ QR และใบ 3 รูป", qrNote: "ติดตามซ้ำใน 24 ชั่วโมง", createdAt: "14:32 น." },
  { id: 2, date: "2026-05-23", reporter: "คุณหวาน", weather: "ฝนช่วงเย็น", area: "แปลง A2", work: "ถอนหญ้า, เบิกวัสดุคลุมดิน", issue: "ดินบางจุดชื้นเกิน", normal: 1180, abnormal: 24, water: "งดน้ำรอบเย็น", fertilizer: "ยังไม่ใส่", disease: "ไม่พบโรคเพิ่ม", experiment: "ทดลองลดน้ำแปลง A2", summary: "รอประเมินความชื้นอีก 24 ชั่วโมง", photos: "ภาพแปลง 5 รูป", summaryPhoto: "ภาพสรุป 1 รูป", workType: "Daily Maintenance", workStatus: "In Progress", plotId: "A2", rowId: "Zone 2", rowsInspected: 28, treesPlanted: 0, laborCount: 4, hoursWorked: 7, materialUsed: "วัสดุคลุมดิน", materialQty: 18, dailyCost: 4200, progressPercent: 64, growthRate: 5.2, survivalRate: 98.0, photoEvidence: "ภาพงาน 4 รูป", soilCondition: "ดินแฉะ", standingWater: "มีน้ำขังเล็กน้อย", fieldWeatherNote: "ฝนตกช่วงเย็น บางจุดชื้นเกินใน Zone 2", weatherPhoto: "ภาพสภาพแปลง 1 รูป", qrType: "QR แปลง", treeId: "PLOT-A2", plotZone: "A2 / Zone 2", treeSpecies: "หางนกยูง", treeStatus: "ปกติ", qrIssue: "ดินชื้นเกินบางจุด", qrPhoto: "ภาพแปลง 2 รูป", qrNote: "งดน้ำรอบเย็น", createdAt: "17:20 น." },
];

const alerts = [
  { title: "แปลง B1 ต้องอนุมัติสูตรปุ๋ย", detail: "ผลทดลอง GS-03 ดีขึ้น แต่ดินชื้นเกินเกณฑ์", level: "ด่วน" },
  { title: "วัสดุคลุมดินเหลือ 18 ม้วน", detail: "คาดใช้หมดภายใน 3 วันทำการ", level: "เตือน" },
  { title: "รถขนย้ายครบกำหนดตรวจ", detail: "ทะเบียน 2กข 4512 เลขไมล์ 68,240 กม.", level: "ติดตาม" },
];

const rdVarieties = [
  { id: "okinawa", name: "มันญี่ปุ่นส้มโอกินาว่า" },
  { id: "purple", name: "มันญี่ปุ่นม่วงเพอเพิลสวีท" },
  { id: "yellow", name: "มันญี่ปุ่นเนื้อเหลือง" },
  { id: "biochar", name: "Biochar Trial" },
  { id: "azolla", name: "Azolla System" },
];

const rdMethods = [
  { id: "drip-bed", name: "แปลงทดลองตามสายน้ำหยด" },
  { id: "horizontal-bag", name: "กระสอบแนวนอน" },
  { id: "pot-bed", name: "กระถาง/แปลงผัก" },
  { id: "basket-3", name: "เข่งเบอร์ 3" },
  { id: "soil-mix", name: "สูตรดินและวัสดุปลูก" },
];

const initialRdExperiments = [
  {
    id: "exp-1",
    name: "การทดลองปลูกมันญี่ปุ่น 4 สายพันธุ์",
    category: "พืชทดลอง",
    varietyId: "okinawa",
    methodId: "drip-bed",
    startDate: "19 พ.ค. 2569",
    plantCount: 5,
    zone: "แปลง A3",
    owner: "ทีม R&D",
    status: "active",
    goal: "เปรียบเทียบการเจริญเติบโตและหาวิธีปลูกที่เหมาะกับฟาร์ม",
    latestResult: "สัปดาห์ที่ 1 แตกยอด 4 ข้อ เถายาวเฉลี่ย 12 ซม.",
    issue: "ไม่พบปัญหาสำคัญ",
  },
  {
    id: "exp-2",
    name: "ชุดทดลองกระสอบแนวนอน",
    category: "พืชทดลอง",
    varietyId: "purple",
    methodId: "horizontal-bag",
    startDate: "19 พ.ค. 2569",
    plantCount: 20,
    zone: "โซนกระสอบ 1",
    owner: "ทีม R&D",
    status: "active",
    goal: "ดูการแตกยอดและการระบายน้ำในกระสอบ",
    latestResult: "แตกยอดดี แต่ความชื้นสูงกว่ากลุ่มอื่น",
    issue: "น้ำขังบางจุดในกระสอบ",
  },
  {
    id: "exp-3",
    name: "ชุดทดลองกระถาง/แปลงผัก",
    category: "พืชทดลอง",
    varietyId: "yellow",
    methodId: "pot-bed",
    startDate: "19 พ.ค. 2569",
    plantCount: 5,
    zone: "แปลงผักทดลอง",
    owner: "ทีมแปลงผัก",
    status: "active",
    goal: "ทดสอบการควบคุมพื้นที่ปลูกและความถี่การให้น้ำ",
    latestResult: "ต้นตั้งตัวได้ แต่การเติบโตช้ากว่าแปลงน้ำหยด",
    issue: "ดินแห้งมากและหน้าดินแข็ง",
  },
  {
    id: "exp-4",
    name: "Biochar Soil Mix Trial",
    category: "วัสดุปรับปรุงดิน",
    varietyId: "biochar",
    methodId: "soil-mix",
    startDate: "23 พ.ค. 2569",
    plantCount: 12,
    zone: "แปลง B1",
    owner: "คุณหวาน",
    status: "active",
    goal: "วัดผลการอุ้มน้ำและการแตกใบใหม่จากสูตรดินผสมไบโอชา",
    latestResult: "สูตร GS-03 เพิ่มการแตกใบใหม่ 8.4%",
    issue: "รออนุมัติสูตรต่อไป",
  },
  {
    id: "exp-5",
    name: "Azolla Ground Cover",
    category: "ระบบพืชเสริม",
    varietyId: "azolla",
    methodId: "soil-mix",
    startDate: "20 พ.ค. 2569",
    plantCount: 1,
    zone: "บ่อทดลอง 2",
    owner: "ทีมระบบน้ำ",
    status: "completed",
    goal: "ประเมินการใช้แหนแดงช่วยคลุมดินและเสริมธาตุอาหาร",
    latestResult: "เก็บข้อมูลครบ รอบต่อไปนำไปเทียบต้นทุน",
    issue: "ไม่พบ",
  },
];

function getRdSummary(experiments) {
  const active = experiments.filter((item) => item.status === "active");
  const issueItems = experiments.filter((item) => item.status !== "archived" && item.issue && !["ไม่พบ", "ไม่พบปัญหาสำคัญ"].includes(item.issue));
  const latest = experiments.find((item) => item.status === "active") || experiments[0];
  return {
    total: experiments.length,
    active: active.length,
    latestResult: latest?.latestResult || "-",
    issues: issueItems.length,
    issueText: issueItems[0]?.issue || "ไม่พบปัญหาสำคัญ",
  };
}

const peopleHrTabs = [
  "Dashboard บุคลากร",
  "ผังองค์กร",
  "ทีมออนไลน์",
  "ผู้จัดการแปลง",
  "คนงาน",
  "ตารางเวร / Attendance",
  "KPI / Performance",
  "ประวัติการทำงาน",
  "เอกสารพนักงาน",
  "สิทธิ์การเข้าถึงระบบ",
  "Welfare & Family",
  "แจ้งเตือน HR",
];

const peopleStatusClasses = {
  Online: "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  Working: "bg-amber-100 text-amber-800 ring-amber-200",
  "In Field": "bg-sky-100 text-sky-800 ring-sky-200",
  Problem: "bg-red-100 text-red-700 ring-red-200",
  Offline: "bg-slate-100 text-slate-600 ring-slate-200",
};

const peopleTeam = [
  {
    id: "HR-001",
    name: "คุณหวาน ใจดี",
    short: "หวาน",
    department: "Field Management",
    position: "ผู้จัดการแปลง",
    status: "Online",
    plot: "แปลง A",
    trees: 936,
    team: 6,
    kpi: 94,
    welfare: "ประกันสังคม, OT, โบนัส",
    startDate: "10 ม.ค. 2569",
    alerts: ["รายงานค้าง"],
    mini: { done: 9, lastCheck: "A1 วันนี้ 14:32", lastReport: "14:32 น.", score: 94 },
    role: "Admin / Manager",
    latestWorkImage: "/public/farm-assets/planting-a.jpg",
    family: { status: "สมรส", children: 1, emergency: "คุณแม่ 089-xxx-1234", education: "ทุนการศึกษาบุตร 1 รายการ", activity: "ร่วมกิจกรรมครอบครัวฟาร์ม" },
  },
  {
    id: "HR-002",
    name: "พี่ไกร แสนดี",
    short: "ไกร",
    department: "Farm Worker",
    position: "หัวหน้าคนงาน",
    status: "In Field",
    plot: "แปลง B",
    trees: 1196,
    team: 4,
    kpi: 88,
    welfare: "ประกันสังคม, ค่าเดินทาง, ยูนิฟอร์ม",
    startDate: "15 ม.ค. 2569",
    alerts: ["มีปัญหาจากแปลง"],
    mini: { done: 7, lastCheck: "B1 วันนี้ 13:10", lastReport: "13:25 น.", score: 88 },
    role: "Staff",
    latestWorkImage: "/public/farm-assets/planting-b.jpg",
    family: { status: "สมรส", children: 2, emergency: "ภรรยา 086-xxx-2345", education: "รอตรวจสิทธิ์ทุน", activity: "อบรมความปลอดภัย" },
  },
  {
    id: "HR-003",
    name: "พี่สมชาย มากมี",
    short: "สมชาย",
    department: "Farm Worker",
    position: "คนงานดูแลแปลง",
    status: "Working",
    plot: "แปลง A",
    trees: 620,
    team: 2,
    kpi: 82,
    welfare: "ประกันสังคม, ค่า OT",
    startDate: "20 ม.ค. 2569",
    alerts: [],
    mini: { done: 5, lastCheck: "A2 วันนี้ 11:50", lastReport: "12:05 น.", score: 82 },
    role: "Staff",
    latestWorkImage: "/public/farm-assets/farm-overview.jpg",
    family: { status: "โสด", children: 0, emergency: "พี่สาว 081-xxx-3456", education: "ไม่มี", activity: "กิจกรรมฟาร์มประจำเดือน" },
  },
  {
    id: "HR-004",
    name: "น.ส.รุ่งนภา สุขใจ",
    short: "รุ่ง",
    department: "Report & Stock",
    position: "ผู้ช่วยบันทึกรายงาน",
    status: "Online",
    plot: "คลังวัสดุ",
    trees: 0,
    team: 1,
    kpi: 91,
    welfare: "ประกันสังคม, วันลาพักร้อน",
    startDate: "1 ก.พ. 2569",
    alerts: ["เอกสารใกล้หมดอายุ"],
    mini: { done: 8, lastCheck: "สต็อกวัสดุ 10:20", lastReport: "10:45 น.", score: 91 },
    role: "Admin / Manager",
    latestWorkImage: "/public/farm-assets/stock-materials-guide.jpg",
    family: { status: "สมรส", children: 1, emergency: "สามี 087-xxx-4567", education: "ทุนบุตรภาคเรียน 1", activity: "CSR โรงเรียนชุมชน" },
  },
  {
    id: "HR-005",
    name: "นายมนต์ชัย พรมดี",
    short: "มนต์",
    department: "Farm Worker",
    position: "คนงานรดน้ำ",
    status: "Problem",
    plot: "แปลง C",
    trees: 1222,
    team: 2,
    kpi: 68,
    welfare: "ประกันสังคม, ยูนิฟอร์ม",
    startDate: "5 ก.พ. 2569",
    alerts: ["KPI ต่ำ", "ยังไม่ส่งรายงาน"],
    mini: { done: 2, lastCheck: "C1 เมื่อวาน", lastReport: "ยังไม่ส่ง", score: 68 },
    role: "Staff",
    latestWorkImage: "/public/farm-assets/planting-c.jpg",
    family: { status: "สมรส", children: 3, emergency: "ภรรยา 082-xxx-5678", education: "ขอพิจารณาทุน 2 ราย", activity: "ติดตามช่วยเหลือพนักงาน" },
  },
  {
    id: "HR-006",
    name: "นายประเสริฐ มานะ",
    short: "เสริฐ",
    department: "Maintenance",
    position: "ช่างซ่อมบำรุง",
    status: "Offline",
    plot: "อุปกรณ์และรถยนต์",
    trees: 0,
    team: 1,
    kpi: 76,
    welfare: "ประกันสังคม, ค่าเดินทาง",
    startDate: "12 ก.พ. 2569",
    alerts: ["ขาดงาน"],
    mini: { done: 1, lastCheck: "รถขนของ 24 พ.ค.", lastReport: "เมื่อวาน 17:15", score: 76 },
    role: "Staff",
    latestWorkImage: "/public/farm-assets/goodseed-logo.png",
    family: { status: "โสด", children: 0, emergency: "บิดา 088-xxx-6789", education: "ไม่มี", activity: "อบรมซ่อมบำรุง" },
  },
];

const peopleHrRecordsStorageKey = "goodseed-people-hr-records";
const peopleHrAttendanceStorageKey = "goodseed-people-hr-attendance";

const defaultAttendanceRecords = [
  { id: "ATT-001", date: "28 พ.ค. 2569", name: "คุณหวาน ใจดี", position: "ผู้จัดการแปลง", shift: "เช้า", time: "07:30 - 17:00", area: "แปลง A", status: "มาทำงาน", note: "ส่งรายงานตรวจแปลงครบ", photo: "/public/farm-assets/planting-a.jpg" },
  { id: "ATT-002", date: "28 พ.ค. 2569", name: "พี่ไกร แสนดี", position: "หัวหน้าคนงาน", shift: "เช้า", time: "08:00 - 17:00", area: "แปลง B", status: "ทำงานภาคสนาม", note: "ตรวจระบบน้ำและรดน้ำช่วงเย็น", photo: "/public/farm-assets/planting-b.jpg" },
  { id: "ATT-003", date: "28 พ.ค. 2569", name: "พี่สมชาย มากมี", position: "คนงานดูแลแปลง", shift: "บ่าย", time: "13:00 - 17:00", area: "แปลง A", status: "รอส่งรายงาน", note: "แนบรูปถอนหญ้าเพิ่มเติม", photo: "/public/farm-assets/farm-overview.jpg" },
];

function readLocalArray(key, fallback) {
  try {
    const raw = localStorage.getItem(key);
    const parsed = raw ? JSON.parse(raw) : null;
    return Array.isArray(parsed) ? parsed : fallback;
  } catch {
    return fallback;
  }
}

function writeLocalArray(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch {
    // localStorage can be unavailable in private browsing; the UI should still work for the session.
  }
}

function readPeopleHrRecords() {
  return readLocalArray(peopleHrRecordsStorageKey, peopleTeam);
}

function writePeopleHrRecords(records) {
  writeLocalArray(peopleHrRecordsStorageKey, records);
}

function readPeopleHrAttendanceRecords() {
  return readLocalArray(peopleHrAttendanceStorageKey, defaultAttendanceRecords);
}

function writePeopleHrAttendanceRecords(records) {
  writeLocalArray(peopleHrAttendanceStorageKey, records);
}

function readImageFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

const hrNotifications = [
  { title: "พนักงานลา", detail: "นายประเสริฐ ลากิจ 1 วัน", tone: "bg-slate-50 text-slate-800" },
  { title: "รายงานค้าง", detail: "คุณหวานยังไม่ปิดรายงานรอบเย็น", tone: "bg-amber-50 text-amber-800" },
  { title: "แจ้งเตือน KPI ต่ำ", detail: "นายมนต์ชัย KPI 68 ต่ำกว่าเกณฑ์", tone: "bg-red-50 text-red-700" },
  { title: "วันเกิดพนักงาน", detail: "พี่ไกร วันเกิด 30 พ.ค. 2569", tone: "bg-sky-50 text-sky-800" },
  { title: "เอกสารใกล้หมดอายุ", detail: "เอกสารประกันของ น.ส.รุ่งนภา", tone: "bg-violet-50 text-violet-800" },
  { title: "แจ้งเตือนสวัสดิการ", detail: "ตรวจสิทธิ์ทุนการศึกษาบุตร 3 ราย", tone: "bg-goodseed-50 text-goodseed-800" },
];

const newsPromotionItems = [
  { type: "ผลผลิตพร้อมขาย", title: "ไม้ล้อมรอบปลูก A พร้อมคัดเกรด", date: "28 พ.ค. 2569", status: "เผยแพร่", image: "/public/farm-assets/planting-a.jpg", summary: "คัดต้นไม้คุณภาพสูงพร้อมส่งมอบสำหรับลูกค้าโครงการจัดสวนและรีสอร์ต", link: "#tree-management" },
  { type: "สินค้าใหม่", title: "ไบโอชา GoodSeed Farm รุ่นทดลองจำหน่าย", date: "1 มิ.ย. 2569", status: "เผยแพร่", image: "/public/farm-assets/product-biochar-packages.png", summary: "ผลิตภัณฑ์จากวัสดุชีวมวลในฟาร์ม สนับสนุนเกษตรยั่งยืน", link: "#organization-goals" },
  { type: "บทความความรู้", title: "การใช้ QR Traceability ในฟาร์มไม้ล้อม", date: "5 มิ.ย. 2569", status: "ซ่อน", image: "/public/farm-assets/goodseed-logo.png", summary: "แนวทางติดตามประวัติต้นไม้ การดูแล และข้อมูลตรวจแปลงแบบเป็นระบบ", link: "#daily-report" },
];

const publicComingSoonProducts = [
  { name: "ไบโอชา (BIOCHAR)", category: "Farm Circular Product", image: "/public/farm-assets/product-biochar-packages.png", description: "ผลิตภัณฑ์คาร์บอนจากวัสดุชีวมวล ช่วยเพิ่มประสิทธิภาพระบบปลูกแบบยั่งยืน", features: ["100% Natural", "Low Carbon", "1 / 5 / 10 / 50 กก."] },
  { name: "น้ำส้มควันไม้ (WOOD VINEGAR)", category: "Natural Extract", image: "/public/farm-assets/product-wood-vinegar.png", description: "สารสกัดจากควันไม้ธรรมชาติ ใช้ดูแลแปลง ลดการพึ่งพาสารเคมี และสนับสนุนระบบฟาร์มปลอดภัย", features: ["สารสกัดธรรมชาติ", "1 / 5 / 10 ลิตร", "ปลอดภัยต่อสิ่งแวดล้อม"] },
  { name: "ผลิตภัณฑ์จากถั่วบราซิล", category: "Ground Cover System", image: "/public/farm-assets/org-goal-products-2026.png", description: "เมล็ดพันธุ์ กิ่งพันธุ์ และต้นกล้าสำหรับพืชคลุมพื้นที่ ช่วยสร้างรายได้เสริมจากระบบฟาร์ม", features: ["เมล็ดพันธุ์", "กิ่งพันธุ์", "ต้นกล้า"] },
  { name: "มันญี่ปุ่น", category: "Premium Crop", image: "/public/farm-assets/product-lineup-board.png", description: "พืชสุขภาพสำหรับตลาดพรีเมียม รองรับการจำหน่ายหัวพันธุ์และผลผลิตจากแปลงทดลอง", features: ["หัวพันธุ์", "ผลผลิต", "ตลาดสุขภาพ"] },
  { name: "ผลิตภัณฑ์จากแหนแดง", category: "Azolla Products", image: "/public/farm-assets/product-lineup-board.png", description: "วัตถุดิบชีวภาพสำหรับระบบเกษตรหมุนเวียน ใช้เลี้ยงสัตว์ ใช้เป็นปุ๋ยสด และช่วยลดต้นทุน", features: ["ลดต้นทุน", "เพิ่มไนโตรเจน", "หมุนเวียนทรัพยากร"] },
  { name: "Sustainable Farming Set", category: "Premium Farm Set", image: "/public/farm-assets/product-sustainable-farming-set.png", description: "ชุดเริ่มต้นเกษตรยั่งยืน รวมผลิตภัณฑ์หลักจากฟาร์มและคู่มือการใช้งาน", features: ["ของขวัญสายเกษตร", "สำหรับผู้เริ่มต้น", "Premium Set"] },
  { name: "ชุดเกษตรยั่งยืน", category: "GOODSEED Bundle", image: "/public/farm-assets/product-sustainable-farming-set.png", description: "ชุดรวมสินค้าแนวคิดเกษตรยั่งยืนสำหรับลูกค้าออนไลน์ เกษตรกร และผู้สนใจปลูกพืช", features: ["น้ำส้มควันไม้", "ไบโอชา", "คู่มือใช้งาน"] },
  { name: "Packaging & Shipping System", category: "Online Commerce", image: "/public/farm-assets/product-online-packaging.png", description: "ระบบบรรจุภัณฑ์และจัดส่งสินค้าออนไลน์ รองรับ Shopee, Lazada, TikTok Shop และเว็บไซต์", features: ["Eco-Friendly", "ส่งทั่วประเทศ", "แพ็กปลอดภัย"] },
];

const companyProfileSections = [
  { title: "เกี่ยวกับเรา", en: "About Us", text: "GoodSeed Farm เป็นฟาร์มไม้ล้อมและฟาร์มเกษตรยั่งยืนที่มุ่งผลิตต้นไม้คุณภาพสูง พร้อมระบบจัดการข้อมูลฟาร์มที่ตรวจสอบย้อนกลับได้" },
  { title: "วิสัยทัศน์", en: "Vision", text: "พัฒนา GoodSeed Farm ให้เป็นต้นแบบฟาร์มไม้ล้อมมาตรฐานสูง เชื่อมโยงตลาดในประเทศและโอกาสส่งออกในอนาคต" },
  { title: "พันธกิจ", en: "Mission", text: "ผลิตต้นไม้คุณภาพสูง จัดการฟาร์มด้วยข้อมูลจริง ใช้ QR Traceability และสร้างผลิตภัณฑ์จากทรัพยากรในฟาร์มอย่างคุ้มค่า" },
  { title: "ธุรกิจหลัก", en: "Core Business", text: "ฟาร์มไม้ล้อม การผลิตต้นไม้คุณภาพสูง ระบบ QR / Traceability และการจัดการฟาร์มแบบมาตรฐาน" },
  { title: "สินค้าและบริการ", en: "Products & Services", text: "ไม้ล้อม ไบโอชา น้ำส้มควันไม้ ถั่วบราซิล แหนแดง ดินหมัก ต้นกล้า และบริการข้อมูลประวัติต้นไม้สำหรับลูกค้า" },
  { title: "จุดเด่นของฟาร์ม", en: "Farm Strengths", text: "มีผังแปลงชัดเจน บันทึกการดูแลรายวัน ตรวจแปลงด้วย QR และเชื่อมข้อมูลจากผู้จัดการถึงเจ้าของฟาร์มแบบรวดเร็ว" },
  { title: "ระบบมาตรฐานและการตรวจสอบย้อนกลับ", en: "Standard & Traceability", text: "ทุกต้นและทุกแปลงสามารถเชื่อมข้อมูลการปลูก การดูแล การตรวจโรคแมลง ภาพหลักฐาน และประวัติย้อนหลังผ่าน QR" },
  { title: "ช่องทางติดต่อ", en: "Contact", text: "GoodSeed Farm | โคกแสมสาร, โคกเจริญ, ลพบุรี | ช่องทางออนไลน์และหน้าฟาร์มสำหรับลูกค้าและคู่ค้า" },
];

const farmAssets = {
  equipment: [
    { id: "EQ-01", name: "เครื่องตัดหญ้า", type: "อุปกรณ์ฟาร์ม", status: "พร้อมใช้งาน", owner: "พี่ไกร", lastCheck: "25 พ.ค. 2569", note: "ลับใบมีดแล้ว พร้อมใช้รอบบ่าย", image: "ภาพตรวจสภาพ 3 รูป", qr: "QR ตรวจความพร้อมอุปกรณ์" },
    { id: "EQ-02", name: "เครื่องพ่นยา", type: "อุปกรณ์ฟาร์ม", status: "กำลังใช้งาน", owner: "พี่สมชาย", lastCheck: "25 พ.ค. 2569", note: "ใช้งานแปลง B1 ตรวจหัวพ่นหลังจบงาน", image: "ภาพใช้งาน 2 รูป", qr: "QR ตรวจความพร้อมอุปกรณ์" },
    { id: "EQ-03", name: "ปั๊มน้ำ", type: "อุปกรณ์ฟาร์ม", status: "พร้อมใช้งาน", owner: "คุณหวาน", lastCheck: "24 พ.ค. 2569", note: "แรงดันน้ำปกติ เปลี่ยนซีลแล้ว", image: "ภาพปั๊มน้ำ 4 รูป", qr: "QR ตรวจความพร้อมอุปกรณ์" },
    { id: "EQ-04", name: "สายยาง / สปริงเกอร์", type: "อุปกรณ์ฟาร์ม", status: "รอซ่อม", owner: "พี่ไกร", lastCheck: "24 พ.ค. 2569", note: "หัวสปริงเกอร์รั่ว 6 จุด รออะไหล่", image: "ภาพจุดรั่ว 5 รูป", qr: "QR ตรวจความพร้อมอุปกรณ์" },
    { id: "EQ-05", name: "เครื่องมือช่าง", type: "อุปกรณ์ฟาร์ม", status: "พร้อมใช้งาน", owner: "คุณหวาน", lastCheck: "23 พ.ค. 2569", note: "จัดเก็บครบตามรายการ", image: "ภาพคลังเครื่องมือ 2 รูป", qr: "QR ตรวจความพร้อมอุปกรณ์" },
  ],
  vehicles: [
    { id: "CAR-01", name: "รถกระบะ", type: "รถยนต์ฟาร์ม", status: "พร้อมใช้งาน", owner: "พี่สมชาย", lastCheck: "25 พ.ค. 2569", note: "เลขไมล์ 68,240 กม. น้ำมัน 75%", image: "ภาพรถและเลขไมล์ 3 รูป", qr: "QR บันทึกการใช้รถยนต์", mileage: "68,240 กม.", fuel: "75%", service: "30 พ.ค. 2569" },
    { id: "CAR-02", name: "รถไถ", type: "รถยนต์ฟาร์ม", status: "กำลังใช้งาน", owner: "พี่ไกร", lastCheck: "25 พ.ค. 2569", note: "ใช้งานปรับพื้นที่ Zone 6", image: "ภาพใช้งาน 2 รูป", qr: "QR บันทึกการใช้รถยนต์", mileage: "1,420 ชม.", fuel: "60%", service: "5 มิ.ย. 2569" },
    { id: "CAR-03", name: "รถขนของ", type: "รถยนต์ฟาร์ม", status: "ชำรุด", owner: "คุณหวาน", lastCheck: "24 พ.ค. 2569", note: "ไฟท้ายไม่ติด รอส่งซ่อม", image: "ภาพจุดชำรุด 4 รูป", qr: "QR บันทึกการใช้รถยนต์", mileage: "42,880 กม.", fuel: "35%", service: "รอซ่อม" },
  ],
};

const allFarmAssets = [...farmAssets.equipment, ...farmAssets.vehicles];

const farmWeatherLocation = {
  name: "GoodSeed Farm",
  nameEn: "GoodSeed Farm",
  label: "โคกแสมสาร, โคกเจริญ, ลพบุรี",
  labelEn: "Khok Samran, Khok Charoen, Lopburi",
  latitude: 15.3793,
  longitude: 100.8187,
};

const fallbackWeather = {
  temperature: 32,
  maxTemp: 35,
  minTemp: 25,
  humidity: 65,
  rainChance: 35,
  rainAmount: 1.2,
  windSpeed: 12,
  windDirection: "ตะวันออกเฉียงเหนือ",
  uvIndex: 8,
  pressure: 1008,
  cloudCover: 42,
  condition: "มีเมฆบางส่วน",
  updatedAt: "ใกล้เคียง Real-time",
};

const weatherHistoryStorageKey = "goodseed-weather-history";

function createFallbackForecastRows(weather = fallbackWeather) {
  return Array.from({ length: 7 }, (_, index) => {
    const date = new Date();
    date.setDate(date.getDate() + index);
    const rainChance = Math.min(95, Math.max(10, Number(weather.rainChance || 35) + (index % 3) * 8 - (index === 0 ? 0 : 6)));
    const maxTemp = Math.round(Number(weather.maxTemp || weather.temperature || 32) + (index % 2));
    const minTemp = Math.round(Number(weather.minTemp || 25) - (index % 2));
    const windSpeed = Math.round(Number(weather.windSpeed || 12) + index);
    const humidity = Math.min(95, Math.max(45, Number(weather.humidity || 65) + (rainChance > 55 ? 8 : 0)));
    return {
      date: date.toISOString().slice(0, 10),
      label: date.toLocaleDateString("th-TH", { weekday: "short", day: "numeric", month: "short" }),
      rainChance,
      maxTemp,
      minTemp,
      windSpeed,
      humidity,
      advice: rainChance >= 60 ? "วางแผนลดน้ำและเลี่ยงพ่นปุ๋ย/ยา" : maxTemp >= 35 ? "ทำงานหนักช่วงเช้าและตรวจความชื้นดิน" : "ทำงานฟาร์มได้ตามแผนปกติ",
    };
  });
}

function readWeatherHistory() {
  return readLocalArray(weatherHistoryStorageKey, []);
}

function writeWeatherHistory(rows) {
  writeLocalArray(weatherHistoryStorageKey, rows);
}

function addWeatherHistoryRecord(weather) {
  const today = new Date().toISOString().slice(0, 10);
  const record = {
    id: `WEA-${Date.now()}`,
    date: today,
    time: new Date().toLocaleTimeString("th-TH", { hour: "2-digit", minute: "2-digit" }),
    temperature: Math.round(Number(weather.temperature || 0)),
    rainChance: Number(weather.rainChance || 0),
    humidity: Number(weather.humidity || 0),
    windSpeed: Number(weather.windSpeed || 0),
    condition: weather.condition || "-",
    advice: getWeatherAdvice(weather).daily,
  };
  const previous = readWeatherHistory().filter((row) => !(row.date === record.date && row.time === record.time));
  const nextRows = [record, ...previous].slice(0, 60);
  writeWeatherHistory(nextRows);
  return nextRows;
}

const qrItems = [
  { title: "QR ประจำต้นไม้", code: "TREE-A1-00482", latest: "ปลูก 12 ม.ค. 2569, ใส่ปุ๋ยล่าสุด 24 พ.ค.", icon: "tree", history: ["24 พ.ค. คุณหวานตรวจใบและราก", "18 พ.ค. พี่ไกรรดน้ำรอบเช้า", "12 พ.ค. บันทึกการเจริญเติบโต +3 ซม."] },
  { title: "QR ประจำแปลง", code: "PLOT-A1", latest: "ตรวจแปลงรายวันครบ 92%, มีปัญหา 2 จุด", icon: "map", history: ["24 พ.ค. ตรวจโรคแมลง", "23 พ.ค. ตรวจหัวน้ำหยด", "22 พ.ค. ถ่ายภาพพื้นที่รวม"] },
  { title: "QR ความพร้อมอุปกรณ์", code: "EQ-PUMP-07", latest: "ปั๊มน้ำพร้อมใช้งาน แรงดันปกติ", icon: "wrench", history: ["24 พ.ค. ทดสอบแรงดัน", "21 พ.ค. เปลี่ยนซีล", "18 พ.ค. ทำความสะอาดไส้กรอง"] },
  { title: "QR การใช้รถยนต์", code: "CAR-4512", latest: "ใช้งานขนไม้ล้อม 2 รอบ เลขไมล์ 68,240 กม.", icon: "truck", history: ["24 พ.ค. พี่สมชายบันทึกเลขไมล์", "22 พ.ค. เติมน้ำมัน 1,800 บาท", "20 พ.ค. ตรวจยางและเบรก"] },
  { title: "QR วัสดุฟาร์ม", code: "MAT-FERT-ORG", latest: "ปุ๋ยอินทรีย์นำเข้า 40 เบิกใช้ 8 กระสอบ", icon: "box", history: ["24 พ.ค. เบิกใช้ 8 กระสอบ", "24 พ.ค. รับเข้า 40 กระสอบ", "19 พ.ค. ตรวจนับคงเหลือ"] },
];

const managerReportQrImages = [
  { title: "บันทึกการใช้รถยนต์", src: "/public/qr-assets/vehicle-usage.png", area: "รถยนต์" },
  { title: "ตรวจเช็คความพร้อมอุปกรณ์", src: "/public/qr-assets/equipment-check.png", area: "อุปกรณ์" },
  { title: "เช็กลิสต์ตรวจแปลงไม้ล้อมประจำวัน", src: "/public/qr-assets/plot-checklist.png", area: "ตรวจแปลง" },
  { title: "บันทึกนำเข้าวัสดุและวัตถุดิบฟาร์ม", src: "/public/qr-assets/stock-input.png", area: "สต็อกวัสดุ" },
  { title: "แบบฟอร์มการปลูก", src: "/public/qr-assets/planting-form.jpg", area: "การปลูก" },
];

const managerReportQrStorageKey = "goodseed-manager-report-qr-gallery";

function readManagerReportQrState() {
  try {
    return JSON.parse(localStorage.getItem(managerReportQrStorageKey) || "{}");
  } catch (error) {
    return {};
  }
}

function writeManagerReportQrState(state) {
  try {
    localStorage.setItem(managerReportQrStorageKey, JSON.stringify(state));
  } catch (error) {
    // Large images can exceed localStorage limits; the UI still works for the current session.
  }
}

const farmLogo = "/public/farm-assets/goodseed-logo.png";
const homeHeroImage = "/public/farm-assets/public-hero-drone-clean.png";
const galleryHeroImage = "/public/farm-assets/home-hero.png";

const aboutImages = {
  hero: "/public/about-assets/about-hero.jpg",
  owner: "/public/about-assets/about-owner.jpg",
  categories: "/public/about-assets/about-categories.jpg",
  vision: "/public/about-assets/about-vision.jpg",
  whoWeAre: "/public/about-assets/who-we-are-goodseed.png",
  productionGoals: "/public/about-assets/about-production-goals.jpg",
  farmGoals: "/public/about-assets/about-farm-goals.jpg",
  treesLandscape: "/public/about-assets/landscape-tree-real.jpg",
  forestTrees: "/public/about-assets/about-forest-trees.jpg",
  fruitTrees: "/public/about-assets/about-fruit-trees.jpg",
  sustainable: "/public/about-assets/about-sustainable.jpg",
  supportingProducts: "/public/about-assets/about-supporting-products.png",
};

const aboutMasterPlans = [
  { title: "รอบปลูก A", code: "A1-A36", area: "พื้นที่ 5 ไร่", total: "936 ต้น", image: "/public/farm-assets/planting-a.jpg", accent: "bg-goodseed-700" },
  { title: "รอบปลูก B", code: "B1-B46", area: "พื้นที่ 5 ไร่", total: "1,196 ต้น", image: "/public/farm-assets/planting-b.jpg", accent: "bg-amber-500" },
  { title: "รอบปลูก C", code: "C1-C47", area: "พื้นที่ 5 ไร่", total: "1,222 ต้น", image: "/public/farm-assets/planting-c.jpg", accent: "bg-rose-500" },
];

const landscapeTreeTypes = ["สะเดา", "จามจุรีสีทอง", "หางนกยูง", "ปีป", "นนทรีสีทอง", "กัลปพฤกษ์", "ชมพูพันธุ์ทิพย์", "ราชพฤกษ์", "ศรีตรัง", "เสลา", "และไม้ล้อมอื่น ๆ"];

const supportingProductNames = ["ไบโอชาร์", "น้ำส้มควันไม้", "แหนแดง", "ถั่วบราซิล", "มันญี่ปุ่น", "ชุดเกษตรยั่งยืน"];

const organizationGoalImages = [
  { title: "ผลผลิตที่คาดว่าจะขายได้ในปี 2026", src: "/public/farm-assets/org-goal-products-2026.png", detail: "ภาพรวมสินค้าที่เกิดจากระบบหมุนเวียนทรัพยากรของฟาร์ม" },
  { title: "น้ำส้มควันไม้", src: "/public/farm-assets/product-wood-vinegar.png", detail: "ผลิตภัณฑ์ Wood Vinegar จากถ่านไม้ธรรมชาติ" },
  { title: "ชุดผลิตภัณฑ์ GoodSeed Farm", src: "/public/farm-assets/product-lineup-board.png", detail: "ภาพรวมผลิตภัณฑ์จากฟาร์มถึงมือลูกค้า" },
  { title: "ไบโอชาแบบกล่อง", src: "/public/farm-assets/product-biochar-box.png", detail: "บรรจุภัณฑ์ Biochar ขนาดใหญ่พร้อมรายละเอียดสินค้า" },
  { title: "ไบโอชาหลายขนาด", src: "/public/farm-assets/product-biochar-packages.png", detail: "แพ็กเกจ 1, 5, 10 และ 50 กิโลกรัม" },
  { title: "ชุดเกษตรยั่งยืน", src: "/public/farm-assets/product-sustainable-farming-set.png", detail: "Sustainable Farming Set สำหรับเกษตรกรและผู้ปลูกพืช" },
  { title: "บรรจุภัณฑ์ขายออนไลน์", src: "/public/farm-assets/product-online-packaging.png", detail: "บรรจุภัณฑ์สำหรับขายออนไลน์และขนส่งสินค้า" },
];

const farmMapImages = [
  { title: "ผังรวมแปลง GoodSeed Farm", src: "/public/farm-assets/farm-overview.jpg", detail: "ภาพผังรวม: รอบปลูก A, รอบปลูก B, รอบปลูก C และโซนให้น้ำ" },
  { title: "รอบปลูก A", src: "/public/farm-assets/planting-a.jpg", detail: "พื้นที่ 5 ไร่ | 36 แถว | A1-A36 | รวม 936 ต้น" },
  { title: "รอบปลูก B", src: "/public/farm-assets/planting-b.jpg", detail: "พื้นที่ 5 ไร่ | 46 แถว | B1-B46 | รวม 1,196 ต้น" },
  { title: "รอบปลูก C", src: "/public/farm-assets/planting-c.jpg", detail: "พื้นที่ 5 ไร่ | 47 แถว | C1-C47 | รวม 1,222 ต้น" },
  { title: "พื้นที่ปลูกรอบโครงข่ายกระจายน้ำ", src: "/public/farm-assets/canal-planting-area.jpg", detail: "แนวปลูกสองฝั่งโครงข่ายกระจายน้ำ: ไม้เศรษฐกิจ ไม้ผล หญ้าแฝก รั้วต้นมันสำปะหลัง และพืชเสริมระบบนิเวศ" },
];

const initialPublicGalleryItems = [
  { id: "gallery-vision-2030", title: "GOODSEED Farm Vision 2030", category: "Company Profile", src: "/public/gallery-media/vision-2030-cover.png" },
  { id: "gallery-vision-mission", title: "วิสัยทัศน์และภารกิจ", category: "Company Profile", src: "/public/gallery-media/vision-mission.jpg" },
  { id: "gallery-fruit-plants", title: "ไม้ผลและพืชเศรษฐกิจ", category: "Farm Media", src: "/public/gallery-media/fruit-plants.jpg" },
  { id: "gallery-forest-trees", title: "ไม้ป่าและไม้เศรษฐกิจ", category: "Farm Media", src: "/public/gallery-media/forest-trees.jpg" },
  { id: "gallery-products", title: "หมวดหมู่ผลิตภัณฑ์ในฟาร์ม", category: "Product Media", src: "/public/gallery-media/farm-products.jpg" },
  { id: "gallery-organic-soil", title: "ลดสารเคมีและฟื้นฟูดิน", category: "Sustainability", src: "/public/gallery-media/organic-soil.jpg" },
  { id: "gallery-production-goals", title: "เป้าหมายการผลิต", category: "Export Vision", src: "/public/gallery-media/production-goals.jpg" },
  { id: "gallery-landscape-trees", title: "ไม้ล้อมเพื่อภูมิทัศน์", category: "Landscape Trees", src: "/public/gallery-media/landscape-trees.jpg" },
];

const plantingRoundSummary = [
  {
    round: "รอบปลูก A",
    rows: 36,
    total: 936,
    ranges: ["A1-A36"],
    species: [
      { name: "จามจุรีทอง", count: 312, rows: "A1-A6, A25-A30" },
      { name: "หางนกยูง", count: 312, rows: "A7-A12, A31-A36" },
      { name: "กัลปพฤกษ์", count: 156, rows: "A13-A18" },
      { name: "มะฮอกกานี", count: 156, rows: "A19-A24" },
    ],
  },
  {
    round: "รอบปลูก B",
    rows: 46,
    total: 1196,
    ranges: ["B1-B46"],
    species: [
      { name: "สะเดา", count: 208, rows: "B1-B8" },
      { name: "หางนกยูง", count: 416, rows: "B9-B16, B25-B32" },
      { name: "จามจุรีทอง", count: 416, rows: "B17-B24, B33-B40" },
      { name: "กัลปพฤกษ์", count: 156, rows: "B41-B46" },
    ],
  },
  {
    round: "รอบปลูก C",
    rows: 47,
    total: 1222,
    ranges: ["C1-C47"],
    species: [
      { name: "สะเดา", count: 624, rows: "C1-C8, C17-C24, C33-C40" },
      { name: "จามจุรีทอง", count: 208, rows: "C9-C16" },
      { name: "ปีบ", count: 208, rows: "C25-C32" },
      { name: "หางนกยูง", count: 156, rows: "C41-C46" },
      { name: "กัลปพฤกษ์", count: 26, rows: "C47" },
    ],
  },
];

const totalTreeBySpecies = [
  { name: "จามจุรีทอง", count: 936 },
  { name: "หางนกยูง", count: 884 },
  { name: "สะเดา", count: 832 },
  { name: "กัลปพฤกษ์", count: 338 },
  { name: "ปีบ", count: 208 },
  { name: "มะฮอกกานี", count: 156 },
];

const statusClasses = {
  "รอดำเนินการ": "bg-slate-100 text-slate-700 ring-slate-200",
  "กำลังทำ": "bg-sky-100 text-sky-700 ring-sky-200",
  "เสร็จแล้ว": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  "มีปัญหา": "bg-red-100 text-red-700 ring-red-200",
  "พร้อมใช้งาน": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  "กำลังใช้งาน": "bg-sky-100 text-sky-700 ring-sky-200",
  "ชำรุด": "bg-red-100 text-red-700 ring-red-200",
  "รอซ่อม": "bg-amber-100 text-amber-800 ring-amber-200",
  "ยังไม่เริ่ม": "bg-slate-100 text-slate-700 ring-slate-200",
  "กำลังดำเนินการ": "bg-sky-100 text-sky-700 ring-sky-200",
  "เลื่อนออกไป": "bg-amber-100 text-amber-800 ring-amber-200",
  "ยกเลิก": "bg-red-100 text-red-700 ring-red-200",
  "ปกติ": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  "ใกล้หมด": "bg-amber-100 text-amber-800 ring-amber-200",
  "ต้องสั่งเพิ่ม": "bg-red-100 text-red-700 ring-red-200",
  "ยังไม่ได้อัปเดต": "bg-slate-100 text-slate-700 ring-slate-200",
  "ตรวจเช็ค": "bg-amber-100 text-amber-800 ring-amber-200",
  "ซ่อมบำรุงแล้ว": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  "ใกล้เกินงบ": "bg-amber-100 text-amber-800 ring-amber-200",
  "เกินงบ": "bg-red-100 text-red-700 ring-red-200",
};

const activityClasses = {
  "วันสิ้นสุดงานสำคัญ": "bg-orange-100 text-orange-800 ring-orange-200",
  "วันตรวจงาน": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  "วันประชุม": "bg-sky-100 text-sky-700 ring-sky-200",
  "วันหยุด": "bg-red-100 text-red-700 ring-red-200",
  "วันจ่ายเงินเดือน": "bg-purple-100 text-purple-700 ring-purple-200",
  "งานทั่วไป": "bg-slate-100 text-slate-700 ring-slate-200",
};

const activityTypes = Object.keys(activityClasses);

const scheduleMonth = [
  ["1", "ตรวจระบบน้ำ A1", "เสร็จแล้ว"],
  ["5", "ใส่ปุ๋ย B1", "กำลังทำ"],
  ["10", "ตัดแต่งไม้ล้อม", "รอดำเนินการ"],
  ["15", "ตรวจสต็อกวัสดุ", "รอดำเนินการ"],
  ["24", "สรุปรายงานเจ้าของ", "เสร็จแล้ว"],
];

const weeklyRows = [
  ["จันทร์", "รดน้ำ A1, ถอนหญ้า A2", "พี่ไกร"],
  ["อังคาร", "ตรวจโรคแมลง B1", "คุณหวาน"],
  ["พุธ", "ใส่ปุ๋ยและถ่ายภาพหลักฐาน", "พี่สมชาย"],
  ["พฤหัส", "ตรวจ QR อุปกรณ์และรถยนต์", "คุณหวาน"],
  ["ศุกร์", "สรุปงานประจำสัปดาห์", "คุณหวาน"],
];

const dailyRows = [
  ["08:00", "รดน้ำแปลง A1", "พี่ไกร", "กำลังทำ"],
  ["10:00", "ตรวจระบบน้ำ A2", "คุณหวาน", "เสร็จแล้ว"],
  ["13:30", "ถอนหญ้า B1", "พี่สมชาย", "รอดำเนินการ"],
  ["16:00", "ถ่ายรูปสรุปงาน", "คุณหวาน", "รอดำเนินการ"],
];

const calendarYear = 2026;
const thaiYear = 2569;
const monthNames = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];
const weekDays = ["จันทร์", "อังคาร", "พุธ", "พฤหัสบดี", "ศุกร์", "เสาร์", "อาทิตย์"];
const monthlyScheduleExample = "/public/farm-assets/monthly-schedule-example.jpg";
const stockMaterialsGuide = "/public/farm-assets/stock-materials-guide.jpg";
const stockMaterialsWithdrawalForm = "/public/farm-assets/stock-materials-withdrawal-form.png";
const managerDailyWorkForm = "/public/farm-assets/manager-daily-work-form.png";
const workerDailyTaskSchedule = "/public/farm-assets/worker-daily-task-schedule.png";

const dailyResponsibilityImages = [
  { title: "สั่งงานพี่ไกร", src: managerDailyWorkForm, detail: "แบบฟอร์มแบ่งช่วงเช้า ช่วงบ่าย สรุปผล และปัญหาที่ต้องติดตาม" },
  { title: "ตารางงานรายวัน", src: workerDailyTaskSchedule, detail: "ตารางเวลา 08.00 - 17.00 น. สำหรับกรอกงาน พื้นที่ ผู้รับผิดชอบ และส่งรายงาน" },
];

const defaultDailyWorkRows = [
  { time: "07.00 - 08.00", managerTask: "ตรวจความพร้อมทีมงาน", managerDetail: "เช็คคนงาน อุปกรณ์ และแผนงานรอบเช้า", workerTask: "เตรียมอุปกรณ์", workerDetail: "ถังน้ำ ปุ๋ย เครื่องมือ และถ่ายรูปก่อนเริ่ม", owner: "คุณหวาน", done: false, note: "" },
  { time: "08.00 - 09.00", managerTask: "มอบหมายงานรดน้ำ", managerDetail: "แปลง A1-A5 ตรวจหัวน้ำหยด", workerTask: "รดน้ำ", workerDetail: "แปลง A1-A5", owner: "พี่ไกร", done: false, note: "" },
  { time: "09.00 - 10.00", managerTask: "ตรวจแปลง", managerDetail: "ตรวจโรคแมลงและต้นผิดปกติ", workerTask: "ถอนหญ้า", workerDetail: "แปลง A6-A10", owner: "พี่สมชาย", done: false, note: "" },
  { time: "10.00 - 11.00", managerTask: "บันทึกภาพหลักฐาน", managerDetail: "ถ่ายรูปงานที่ทำและปัญหาที่พบ", workerTask: "ใส่ปุ๋ย", workerDetail: "แปลง B1 ตามแผนทดลอง", owner: "พี่ไกร", done: false, note: "" },
  { time: "11.00 - 12.00", managerTask: "สรุปงานช่วงเช้า", managerDetail: "รวบรวมข้อมูลเตรียมส่งเจ้าของ", workerTask: "เก็บอุปกรณ์", workerDetail: "ล้างอุปกรณ์และจัดเก็บ", owner: "พี่สมชาย", done: false, note: "" },
  { time: "12.00 - 13.00", managerTask: "พักกลางวัน", managerDetail: "พักกลางวัน", workerTask: "พักกลางวัน", workerDetail: "พักกลางวัน", owner: "-", done: false, note: "" },
  { time: "13.00 - 14.00", managerTask: "ตรวจสต็อกวัสดุ", managerDetail: "นำเข้าและเบิกใช้วัตถุดิบประจำวัน", workerTask: "เบิกวัสดุ", workerDetail: "ปุ๋ยอินทรีย์ วัสดุคลุมดิน", owner: "คุณหวาน", done: false, note: "" },
  { time: "14.00 - 15.00", managerTask: "ติดตามงานปลูก", managerDetail: "ตรวจคุณภาพการปลูกและระยะห่าง", workerTask: "ปลูกต้นไม้", workerDetail: "รอบปลูก B", owner: "พี่ไกร", done: false, note: "" },
  { time: "15.00 - 16.00", managerTask: "ตรวจปัญหา", managerDetail: "บันทึกงานไม่เสร็จ / พบปัญหา", workerTask: "ตรวจโรคแมลง", workerDetail: "แปลง A2, B1", owner: "พี่สมชาย", done: false, note: "" },
  { time: "16.00 - 17.00", managerTask: "สรุปรายงาน", managerDetail: "ส่งรายงานประจำวันพร้อมรูปภาพ", workerTask: "เก็บงานและส่งรูป", workerDetail: "ถ่ายรูปหลังทำงาน", owner: "คุณหวาน", done: false, note: "" },
];

const maySchedule = {
  10: "เริ่มต้นงาน",
  11: "เข้าตรวจงาน\nวางแผนประชุมงานรายสัปดาห์",
  12: "ปลูกต้นไม้\n200 ต้น\nแถว B1-B46\nตรวจแปลง A1-A5",
  13: "ปลูกต้นไม้\n100 ต้น\nแถว B1-B46\nตรวจแปลง A6-A10",
  14: "ปลูกต้นไม้\n200 ต้น\nแถว B1-B46\nตรวจแปลง A11-A15",
  15: "ปลูกต้นไม้\n200 ต้น\nแถว B1-B46\nตรวจแปลง A16-A20",
  16: "ปลูกต้นไม้\n200 ต้น\nแถว B1-B46\nตรวจแปลง A21-A25",
  17: "ปลูกต้นไม้\n200 ต้น\nแถว B1-B46\nตรวจแปลง A26-A30",
  18: "เข้าตรวจงาน\nวางแผนประชุมงานรายสัปดาห์\nตรวจแปลง A30-A36\nสรุปผลทดลองประจำสัปดาห์",
  19: "วันหยุด",
  20: "เพาะเลี้ยงแหนแดง\nทดลองปลูกมันในกระสอบ\nปลูกไม้ล้อมในเข่ง\nตรวจแปลง B1-B12",
  21: "หว่านเมล็ดปอเทือง\nปลูกถั่วแระญี่ปุ่น\nแปลง A3 ถึง A36\nตรวจแปลง B13-B24",
  22: "ปลูกถั่วบราซิลรอบโคนต้นไม้\nตรวจแปลง B25-B37",
  23: "วัดพื้นที่เตรียมปลูกต้นไม้รอบโครงข่ายกระจายน้ำ\nตรวจแปลง B38-B46\nตรวจเช็คอุปกรณ์ประจำสัปดาห์",
  24: "วันหยุด",
  25: "เข้าตรวจงาน\nวางแผนประชุมงานรายสัปดาห์\nสรุปผลทดลองประจำสัปดาห์",
  28: "ตรวจเช็คอุปกรณ์ประจำสัปดาห์",
  29: "เข้าตรวจงาน\nวางแผนประชุมงานรายสัปดาห์",
  30: "วันหยุด",
  31: "เข้าตรวจงาน\nสรุปผลทดลองประจำสัปดาห์\nประชุมวางแผนงานเดือนมิถุนายน",
};

function buildInitialCalendar() {
  return monthNames.reduce((calendar, _month, monthIndex) => {
    calendar[monthIndex] = {};
    if (monthIndex === 4) {
      calendar[monthIndex] = maySchedule;
    }
    return calendar;
  }, {});
}

function getCalendarDays(year, monthIndex) {
  const firstDay = new Date(year, monthIndex, 1);
  const daysInMonth = new Date(year, monthIndex + 1, 0).getDate();
  const mondayFirstOffset = (firstDay.getDay() + 6) % 7;
  return [
    ...Array.from({ length: mondayFirstOffset }, () => null),
    ...Array.from({ length: daysInMonth }, (_, index) => index + 1),
  ];
}

function Badge({ children, className = "" }) {
  return <span className={`inline-flex items-center rounded-full px-2.5 py-1 text-xs font-bold ring-1 ${className}`}>{children}</span>;
}

function StatusBadge({ status }) {
  return <Badge className={statusClasses[status] || "bg-slate-100 text-slate-700 ring-slate-200"}>{status}</Badge>;
}

function downloadFile(filename, content, type) {
  const blob = new Blob([content], { type });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(link.href);
}

function Sidebar({ open, setOpen, viewMode, role, t }) {
  if (viewMode === "mobile") return null;

  const isTablet = viewMode === "tablet";
  const items = visibleNavItems(role);
  const asideClass = isTablet
    ? "sticky top-0 z-40 flex h-screen w-20 shrink-0 flex-col bg-goodseed-900 text-white shadow-2xl"
    : `fixed inset-y-0 left-0 z-40 flex w-72 transform flex-col bg-goodseed-900 text-white shadow-2xl transition lg:sticky lg:top-0 lg:h-screen lg:translate-x-0 ${open ? "translate-x-0" : "-translate-x-full"}`;

  return (
    <>
      {!isTablet && <div className={`fixed inset-0 z-30 bg-goodseed-900/40 transition lg:hidden ${open ? "opacity-100" : "pointer-events-none opacity-0"}`} onClick={() => setOpen(false)} />}
      <aside className={asideClass}>
        <div className={`flex items-center border-b border-white/10 ${isTablet ? "justify-center p-4" : "justify-between p-5"}`}>
          <div className={`flex items-center ${isTablet ? "justify-center" : "gap-3"}`}>
            <img src={farmLogo} alt="GoodSeed Farm logo" className={`${isTablet ? "h-11 w-11" : "h-12 w-12"} rounded-lg object-cover ring-1 ring-white/20`} />
            {!isTablet && <div><p className="text-lg font-extrabold leading-tight">GoodSeed</p><p className="text-xs text-goodseed-100">Farm Management</p></div>}
          </div>
          {!isTablet && <button className="rounded-lg p-2 lg:hidden" onClick={() => setOpen(false)} aria-label="ปิดเมนู"><Icon name="x" /></button>}
        </div>
        <nav className={`thin-scrollbar flex-1 space-y-1 overflow-y-auto ${isTablet ? "p-2" : "p-3"}`}>
          {items.map(([label, icon, id], index) => {
            const translatedLabel = t(`internalNav.${id}`, label);
            return (
            <a key={id} href={`#${id}`} title={translatedLabel} onClick={() => setOpen(false)} className={`flex items-center rounded-lg text-sm font-medium transition ${isTablet ? "justify-center px-2 py-3" : "gap-3 px-3 py-3"} ${index === 0 ? "bg-white text-goodseed-900" : "text-goodseed-50 hover:bg-white/10"}`}>
              <Icon name={icon} className="h-5 w-5 shrink-0" /><span className={`${isTablet ? "sr-only" : "min-w-0 truncate"}`}>{translatedLabel}</span>
            </a>
          )})}
        </nav>
        {!isTablet && <div className="border-t border-white/10 p-4">
          <div className="rounded-lg bg-white/10 p-3"><p className="text-sm font-semibold">{t("system.status")}</p><p className="mt-1 text-xs text-goodseed-100">{t("system.sync")}</p></div>
        </div>}
      </aside>
    </>
  );
}

function BottomNavigation({ role, t }) {
  const items = visibleNavItems(role).slice(0, 5);
  return (
    <nav className="fixed inset-x-0 bottom-0 z-50 border-t border-goodseed-100 bg-white/95 px-2 py-2 shadow-2xl backdrop-blur">
      <div className="mx-auto grid max-w-[430px] grid-cols-5 gap-1">
        {items.map(([label, icon, id], index) => (
          <a key={id} href={`#${id}`} className={`flex flex-col items-center justify-center rounded-lg px-1 py-2 text-[10px] font-extrabold ${index === 0 ? "bg-goodseed-700 text-white" : "text-goodseed-800 hover:bg-goodseed-50"}`}>
            <Icon name={icon} className="mb-1 h-5 w-5" />
            <span className="max-w-full truncate">{t(`internalNav.${id}`, label).split(" ")[0]}</span>
          </a>
        ))}
      </div>
    </nav>
  );
}

function PreviewToggle({ viewMode, setViewMode, t }) {
  return (
    <div className="rounded-lg border border-goodseed-100 bg-white p-1 shadow-sm">
      <div className="grid grid-cols-3 gap-1">
        {previewModes.map((mode) => (
          <button
            key={mode.id}
            onClick={() => setViewMode(mode.id)}
            title={mode.hint}
            className={`inline-flex items-center justify-center gap-2 rounded-md px-3 py-2 text-xs font-extrabold transition ${
              viewMode === mode.id ? "bg-goodseed-700 text-white shadow-sm" : "text-goodseed-800 hover:bg-goodseed-50"
            }`}
          >
            <Icon name={mode.icon} className="h-4 w-4" />
            <span className="hidden sm:inline">{t(`preview.${mode.id}`, mode.label)}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function SectionHeader({ title, subtitle, action }) {
  return (
    <div className="mb-5 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
      <div className="min-w-0 max-w-3xl">
        <h2 className="text-xl font-extrabold leading-snug text-goodseed-900 sm:text-2xl">{title}</h2>
        {subtitle && <p className="mt-2 max-w-2xl text-sm font-semibold leading-7 text-goodseed-700">{subtitle}</p>}
      </div>
      {action && <div className="shrink-0">{action}</div>}
    </div>
  );
}

function BiLabel({ th, en, inline = false }) {
  return (
    <span className={inline ? "inline-flex flex-wrap items-baseline gap-1" : "block"}>
      <span>{th}</span>
      <span className={`${inline ? "" : "mt-0.5 block"} text-[11px] font-bold tracking-normal text-goodseed-600`}>{en}</span>
    </span>
  );
}

function DashboardCard({ label, value, unit, icon, tone = "bg-white text-goodseed-800" }) {
  return (
    <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft">
      <div className="flex items-start justify-between gap-4">
        <div><p className="text-sm font-bold text-goodseed-700">{label}</p><p className="mt-2 text-3xl font-extrabold text-goodseed-900">{value} <span className="text-sm font-semibold text-goodseed-600">{unit}</span></p></div>
        <div className={`grid h-11 w-11 place-items-center rounded-lg ${tone}`}><Icon name={icon} /></div>
      </div>
    </div>
  );
}

function MiniMetric({ label, value, danger }) {
  return <div className={`rounded-lg p-4 ${danger ? "bg-red-50 text-red-800" : "bg-goodseed-50 text-goodseed-900"}`}><p className="text-xs font-bold leading-5">{label}</p><p className="mt-2 break-words text-xl font-extrabold leading-tight">{value}</p></div>;
}

function windDirectionText(degrees = 0) {
  const directions = ["เหนือ", "ตะวันออกเฉียงเหนือ", "ตะวันออก", "ตะวันออกเฉียงใต้", "ใต้", "ตะวันตกเฉียงใต้", "ตะวันตก", "ตะวันตกเฉียงเหนือ"];
  return directions[Math.round(degrees / 45) % 8];
}

function getWeatherAdvice(weather = fallbackWeather) {
  const water = weather.rainChance >= 60 || weather.rainAmount >= 5 ? ["ต้องระวัง", "มีโอกาสฝน ควรลดรอบรดน้ำ"] : weather.temperature >= 34 ? ["เหมาะ", "อากาศร้อน ควรรดน้ำช่วงเช้าหรือเย็น"] : ["เหมาะ", "รดน้ำตามแผนปกติ"];
  const planting = weather.uvIndex >= 9 || weather.temperature >= 36 ? ["ต้องระวัง", "แดดแรง ควรปลูกช่วงเช้าหรือเย็น"] : ["เหมาะ", "เหมาะกับการปลูกและย้ายกล้า"];
  const spray = weather.windSpeed >= 20 || weather.rainChance >= 50 ? ["ไม่เหมาะ", "หลีกเลี่ยงการพ่นปุ๋ย/พ่นยา"] : ["เหมาะ", "พ่นได้ แต่ควรติดตามลมก่อนเริ่มงาน"];
  const risks = [
    weather.rainAmount >= 10 || weather.rainChance >= 70 ? "เสี่ยงฝนตกหนัก" : null,
    weather.windSpeed >= 20 ? "เสี่ยงลมแรง" : null,
    weather.uvIndex >= 8 ? "UV สูง ระวังแดดจัด" : null,
  ].filter(Boolean);
  return { water, planting, spray, risks: risks.length ? risks : ["ไม่มีความเสี่ยงรุนแรง"], daily: "ตรวจความชื้นดินก่อนรดน้ำ และวางงานพ่นช่วงลมนิ่ง" };
}

function RiskBadge({ status, language = "th" }) {
  const cls = status === "เหมาะ" ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : status === "ต้องระวัง" ? "bg-amber-100 text-amber-800 ring-amber-200" : "bg-red-100 text-red-700 ring-red-200";
  const label = language === "en" ? ({ "เหมาะ": "Good", "ต้องระวัง": "Caution", "ไม่เหมาะ": "Avoid" }[status] || status) : status;
  return <Badge className={cls}>{label}</Badge>;
}

function KpiCard({ label, value, unit, hint, icon, tone, danger }) {
  return (
    <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft">
      <div className="flex items-start gap-4">
        <div className={`grid h-14 w-14 shrink-0 place-items-center rounded-full ${tone}`}><Icon name={icon} className="h-7 w-7" /></div>
        <div className="min-w-0">
          <p className="text-sm font-bold text-slate-700">{label}</p>
          <p className={`mt-1 text-3xl font-extrabold ${danger ? "text-red-700" : "text-goodseed-950"}`}>{value} <span className="text-sm font-bold text-goodseed-600">{unit}</span></p>
          <p className={`mt-2 text-xs font-semibold ${danger ? "text-red-600" : "text-goodseed-700"}`}>{hint}</p>
        </div>
      </div>
    </div>
  );
}

function DashboardPanel({ id, title, action, children, className = "" }) {
  return (
    <div id={id} className={`rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft sm:p-6 ${className}`}>
      <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <h3 className="min-w-0 text-lg font-extrabold leading-snug text-goodseed-950">{title}</h3>
        {action && <div className="shrink-0">{action}</div>}
      </div>
      {children}
    </div>
  );
}

function ProgressRow({ label, value, total, color }) {
  const percent = Math.min(100, Math.round((value / total) * 100));
  return (
    <div>
      <div className="mb-2 flex items-center justify-between gap-3 text-sm">
        <span className="font-bold text-goodseed-800">{label}</span>
        <span className="font-extrabold text-goodseed-950">{value.toLocaleString("th-TH")} ต้น</span>
      </div>
      <div className="h-2.5 overflow-hidden rounded-full bg-slate-100">
        <div className={`h-full rounded-full ${color}`} style={{ width: `${percent}%` }} />
      </div>
    </div>
  );
}

function MaterialTable({ viewMode }) {
  const rows = [
    ["ปุ๋ยคอก", "1,200 กก.", "350 กก.", "850 กก."],
    ["ปุ๋ยเคมี 15-15-15", "500 กก.", "200 กก.", "300 กก."],
    ["ดินปลูก", "2.5 ตัน", "1 ตัน", "1.5 ตัน"],
    ["สารเคมีกำจัดแมลง", "30 ลิตร", "10 ลิตร", "20 ลิตร"],
    ["น้ำหมักชีวภาพ", "60 ลิตร", "25 ลิตร", "35 ลิตร"],
  ];

  if (viewMode === "mobile") {
    return (
      <div className="space-y-3">
        {rows.map(([name, inStock, used, remain]) => (
          <div key={name} className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-3">
            <p className="font-extrabold text-goodseed-900">{name}</p>
            <div className="mt-3 grid grid-cols-3 gap-2 text-center text-xs font-bold text-goodseed-700">
              <span className="rounded-md bg-white p-2">นำเข้า<br />{inStock}</span>
              <span className="rounded-md bg-white p-2">เบิกใช้<br />{used}</span>
              <span className="rounded-md bg-white p-2">คงเหลือ<br />{remain}</span>
            </div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="overflow-hidden rounded-lg border border-goodseed-100">
      <table className="w-full text-left text-sm">
        <thead className="bg-goodseed-50 text-goodseed-800">
          <tr>{["รายการ", "นำเข้า", "เบิกใช้", "คงเหลือ"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr>
        </thead>
        <tbody className="divide-y divide-goodseed-100">
          {rows.map((row) => <tr key={row[0]}>{row.map((cell, index) => <td key={cell} className={`px-3 py-3 ${index === 0 ? "font-bold text-goodseed-900" : "text-slate-700"}`}>{cell}</td>)}</tr>)}
        </tbody>
      </table>
    </div>
  );
}

function MiniCalendar() {
  const days = Array.from({ length: 35 }, (_, index) => index + 1);
  const marked = { 5: "bg-goodseed-100 text-goodseed-800", 12: "bg-blue-100 text-blue-700", 20: "bg-goodseed-700 text-white", 24: "bg-amber-100 text-amber-800", 30: "bg-red-100 text-red-700" };
  return (
    <div>
      <div className="grid grid-cols-7 gap-1 text-center text-xs font-extrabold text-goodseed-700">
        {["จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"].map((day) => <span key={day}>{day}</span>)}
      </div>
      <div className="mt-2 grid grid-cols-7 gap-1 text-center text-sm">
        {days.map((day) => <span key={day} className={`rounded-md px-2 py-2 font-bold ${marked[day] || "text-slate-600 hover:bg-goodseed-50"}`}>{day <= 31 ? day : ""}</span>)}
      </div>
      <div className="mt-4 grid gap-2 text-xs font-semibold text-slate-600 sm:grid-cols-2">
        <span><i className="mr-2 inline-block h-2 w-2 rounded-full bg-goodseed-600" />งานวันนี้</span>
        <span><i className="mr-2 inline-block h-2 w-2 rounded-full bg-blue-500" />งานสำคัญ</span>
        <span><i className="mr-2 inline-block h-2 w-2 rounded-full bg-amber-500" />นัดหมาย</span>
        <span><i className="mr-2 inline-block h-2 w-2 rounded-full bg-red-500" />ปัญหา</span>
      </div>
    </div>
  );
}

function DonutChart() {
  return (
    <div className="flex flex-col items-center justify-center gap-4 sm:flex-row">
      <div className="grid h-40 w-40 place-items-center rounded-full" style={{ background: "conic-gradient(#2f8f46 0 76%, #f5c84c 76% 89%, #ef4444 89% 100%)" }}>
        <div className="grid h-24 w-24 place-items-center rounded-full bg-white text-center shadow-inner">
          <p className="text-3xl font-extrabold text-goodseed-950">145</p>
          <p className="text-xs font-bold text-goodseed-700">งานรวม</p>
        </div>
      </div>
      <div className="space-y-3 text-sm font-bold">
        <p><span className="mr-2 inline-block h-3 w-3 rounded-sm bg-goodseed-600" />เสร็จแล้ว 125 (86%)</p>
        <p><span className="mr-2 inline-block h-3 w-3 rounded-sm bg-amber-400" />กำลังทำ 21 (14%)</p>
        <p><span className="mr-2 inline-block h-3 w-3 rounded-sm bg-red-500" />ค้าง 19 (13%)</p>
      </div>
    </div>
  );
}

function BarChart() {
  const months = [["ม.ค.", 54, 38], ["ก.พ.", 62, 42], ["มี.ค.", 69, 45], ["เม.ย.", 74, 48], ["พ.ค.", 86, 52], ["มิ.ย.", 78, 46]];
  return (
    <div className="flex h-44 items-end gap-3 rounded-lg bg-goodseed-50 p-4">
      {months.map(([month, income, expense]) => (
        <div key={month} className="flex flex-1 flex-col items-center gap-2">
          <div className="flex h-28 items-end gap-1">
            <span className="w-4 rounded-t bg-goodseed-600" style={{ height: `${income}%` }} />
            <span className="w-4 rounded-t bg-amber-400" style={{ height: `${expense}%` }} />
          </div>
          <span className="text-xs font-bold text-goodseed-700">{month}</span>
        </div>
      ))}
    </div>
  );
}

function DashboardQuickActions({ role }) {
  const exportDate = formatTopbarDate("th");
  const actions = [
    ["บันทึกรายงานประจำวัน", "file", "daily-report"],
    ["สแกน QR", "qr", "tree-management"],
    ["เพิ่มงานใหม่", "check", "daily-work"],
    ["นำเข้าวัสดุ", "truck", "inventory"],
    ["เบิกใช้วัสดุ", "box", "inventory"],
    ["รายงานผู้จัดการ", "camera", "owner-review"],
  ].filter(([, , id]) => canAccess(role, id));
  const canExport = ["owner", "admin", "manager"].includes(role);

  return (
    <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-9">
      {actions.map(([label, icon, id]) => (
        <a key={label} href={`#${id}`} className="flex items-center gap-3 rounded-lg border border-goodseed-100 bg-white p-4 font-extrabold text-goodseed-800 shadow-soft hover:bg-goodseed-50 xl:col-span-1">
          <span className="grid h-11 w-11 shrink-0 place-items-center rounded-lg bg-goodseed-100"><Icon name={icon} /></span>
          <span className="min-w-0 text-sm">{label}</span>
        </a>
      ))}
      {canExport && ["PDF", "Excel", "Word"].map((label) => (
        <button key={label} onClick={() => downloadFile(`goodseed-dashboard.${label.toLowerCase()}`, `GoodSeed Farm Dashboard Export\nวันที่ ${exportDate}`, "text/plain;charset=utf-8")} className="rounded-lg border border-goodseed-100 bg-white p-4 text-center font-extrabold text-goodseed-800 shadow-soft hover:bg-goodseed-50">
          <Icon name="download" className="mx-auto mb-2 h-6 w-6" />{label}
        </button>
      ))}
    </div>
  );
}

function DashboardTaskTable({ tasks }) {
  return (
    <div className="thin-scrollbar overflow-x-auto rounded-lg border border-goodseed-100">
      <table className="min-w-[720px] w-full text-left text-sm">
        <thead className="bg-goodseed-50 text-goodseed-800"><tr>{["ลำดับ", "งานที่ต้องทำ", "แปลง", "ผู้รับผิดชอบ", "สถานะ"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr></thead>
        <tbody className="divide-y divide-goodseed-100">
          {tasks.map((task, index) => <tr key={task.id}><td className="px-3 py-3">{index + 1}</td><td className="px-3 py-3 font-bold text-goodseed-900">{task.duty}</td><td className="px-3 py-3">{task.area}</td><td className="px-3 py-3">{task.owner}</td><td className="px-3 py-3"><StatusBadge status={task.status} /></td></tr>)}
        </tbody>
      </table>
    </div>
  );
}

function TaskSummaryCards({ tasks }) {
  return (
    <div className="space-y-3">
      {tasks.map((task, index) => (
        <div key={task.id} className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-3">
          <div className="flex items-start justify-between gap-3">
            <p className="text-xs font-extrabold text-goodseed-600">งานที่ {index + 1}</p>
            <StatusBadge status={task.status} />
          </div>
          <p className="mt-2 font-extrabold text-goodseed-950">{task.duty}</p>
          <div className="mt-3 grid grid-cols-2 gap-2 text-xs font-bold text-goodseed-700">
            <span className="rounded-md bg-white p-2">แปลง: {task.area}</span>
            <span className="rounded-md bg-white p-2">ผู้รับผิดชอบ: {task.owner}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function ControlCard({ label, value, unit, hint, icon, tone, href, onOpen }) {
  const content = (
    <>
      <div className={`grid h-14 w-14 shrink-0 place-items-center rounded-full ${tone}`}><Icon name={icon} className="h-7 w-7" /></div>
      <div className="min-w-0">
        <p className="text-sm font-bold text-slate-700">{label}</p>
        <p className="mt-1 text-3xl font-black leading-tight text-goodseed-950">{value} <span className="text-sm font-bold text-goodseed-600">{unit}</span></p>
        <p className="mt-2 line-clamp-2 text-xs font-semibold text-goodseed-700">{hint}</p>
      </div>
    </>
  );
  const className = "group flex h-full items-start gap-4 rounded-lg border border-goodseed-100 bg-white p-4 text-left shadow-soft transition hover:-translate-y-0.5 hover:border-goodseed-300 hover:shadow-lg";
  if (href) return <a href={href} className={className}>{content}</a>;
  return <button onClick={onOpen} className={className}>{content}</button>;
}

function ControlWidget({ title, action, children, className = "", onOpen }) {
  return (
    <section className={`rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft transition hover:border-goodseed-200 sm:p-5 ${className}`}>
      <div className="mb-4 flex items-start justify-between gap-3">
        <button onClick={onOpen} className="min-w-0 text-left">
          <h3 className="text-lg font-black leading-snug text-goodseed-950">{title}</h3>
        </button>
        {action && <div className="shrink-0">{action}</div>}
      </div>
      {children}
    </section>
  );
}

function SmartFarmDetailModal({ detail, onClose }) {
  if (!detail) return null;
  return (
    <div className="fixed inset-0 z-[90] flex items-end bg-goodseed-950/55 p-3 backdrop-blur-sm sm:items-center sm:justify-center">
      <div className="max-h-[88vh] w-full max-w-3xl overflow-hidden rounded-lg bg-white shadow-2xl">
        <div className="flex items-start justify-between gap-4 border-b border-goodseed-100 p-5">
          <div>
            <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Detail On Demand</Badge>
            <h3 className="mt-3 text-2xl font-black text-goodseed-950">{detail.title}</h3>
            <p className="mt-1 text-sm font-bold text-goodseed-600">{detail.subtitle}</p>
          </div>
          <button onClick={onClose} className="rounded-lg bg-goodseed-50 p-2 text-goodseed-800 ring-1 ring-goodseed-100" aria-label="ปิด"><Icon name="x" /></button>
        </div>
        <div className="thin-scrollbar max-h-[68vh] overflow-auto p-5">
          <div className="grid gap-3 sm:grid-cols-2">
            {detail.items.map((item) => (
              <div key={item.label} className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
                <p className="text-xs font-extrabold text-goodseed-600">{item.label}</p>
                <p className="mt-2 text-lg font-black leading-tight text-goodseed-950">{item.value}</p>
                {item.note && <p className="mt-2 text-sm font-semibold leading-6 text-goodseed-700">{item.note}</p>}
              </div>
            ))}
          </div>
          {detail.href && <a href={detail.href} onClick={onClose} className="mt-5 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-4 py-3 text-sm font-black text-white"><Icon name="layout" />เปิดหน้า Detail</a>}
        </div>
      </div>
    </div>
  );
}

function DashboardMiniTaskList({ tasks }) {
  return (
    <div className="space-y-2">
      {tasks.slice(0, 4).map((task) => (
        <a key={task.id} href="#daily-work" className="grid grid-cols-[1fr_auto] gap-3 rounded-lg bg-goodseed-50 px-3 py-2 transition hover:bg-goodseed-100">
          <div className="min-w-0">
            <p className="truncate text-sm font-black text-goodseed-950">{task.duty}</p>
            <p className="text-xs font-bold text-goodseed-600">{task.area} / {task.owner}</p>
          </div>
          <StatusBadge status={task.status} />
        </a>
      ))}
    </div>
  );
}

function MiniDonut({ center = "42", label = "แปลง" }) {
  return (
    <div className="flex items-center gap-5">
      <div className="relative grid h-36 w-36 place-items-center rounded-full" style={{ background: "conic-gradient(#2f8f46 0 76%, #f3b537 76% 92%, #ef4444 92% 100%)" }}>
        <div className="grid h-24 w-24 place-items-center rounded-full bg-white text-center shadow-inner">
          <p className="text-3xl font-black text-goodseed-950">{center}</p>
          <p className="text-xs font-extrabold text-goodseed-700">{label}</p>
        </div>
      </div>
      <div className="space-y-3 text-sm font-bold text-goodseed-800">
        <p><span className="mr-2 inline-block h-3 w-3 rounded-sm bg-goodseed-600" />ตรวจแล้ว 32 (76%)</p>
        <p><span className="mr-2 inline-block h-3 w-3 rounded-sm bg-amber-400" />ยังไม่ตรวจ 8 (19%)</p>
        <p><span className="mr-2 inline-block h-3 w-3 rounded-sm bg-red-500" />มีปัญหา 2 (5%)</p>
      </div>
    </div>
  );
}

function OnlineTeamWidget({ onOpen, activeUsers }) {
  return (
    <div className="space-y-2">
      <button onClick={onOpen} className="flex w-full items-center justify-between rounded-lg bg-goodseed-50 p-3 text-left">
        <div><p className="text-sm font-black text-goodseed-950">ทีมออนไลน์</p><p className="text-xs font-bold text-goodseed-600">Active Users / {activeUsers.length} คน</p></div>
        <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Live</Badge>
      </button>
      {activeUsers.slice(0, 3).map((user) => (
        <div key={user.email || user.name} className="flex items-center gap-3 rounded-lg bg-white p-2 ring-1 ring-goodseed-100">
          <span className="h-2.5 w-2.5 rounded-full bg-goodseed-500" />
          <div className="min-w-0"><p className="truncate text-sm font-black text-goodseed-900">{user.name}</p><p className="truncate text-xs font-bold text-goodseed-600">{user.activity}</p></div>
        </div>
      ))}
    </div>
  );
}

function Dashboard({ reports, tasks, viewMode, role, rdExperiments, authProfile }) {
  const [detail, setDetail] = useState(null);
  const [syncTime, setSyncTime] = useState(() => new Date());
  const [pendingAccessCount, setPendingAccessCount] = useState(0);
  const [activeUsers, setActiveUsers] = useState(() => authProfile ? [{
    id: authProfile.id || authProfile.email,
    name: profileDisplayName(authProfile),
    email: authProfile.email || "",
    role: roleInfo(role).label,
    activity: `กำลังดู Dashboard / ${roleInfo(role).label}`,
    page: "dashboard",
    lastSeen: new Date().toISOString(),
  }] : []);
  const [presenceStatus, setPresenceStatus] = useState("mock");
  const latestReport = reports[0];
  const dashboardWeather = latestReport.weatherSnapshot || fallbackWeather;
  const weatherAdvice = getWeatherAdvice(dashboardWeather);
  const rdSummary = getRdSummary(rdExperiments);
  const currentUserName = profileDisplayName(authProfile);
  const syncLabel = syncTime.toLocaleTimeString("th-TH", { hour: "2-digit", minute: "2-digit" });
  const todayReportCount = reports.filter((report) => report.date === latestReport.date).length;
  const completed = tasks.filter((task) => task.status === "เสร็จแล้ว").length;
  const doing = tasks.filter((task) => task.status === "กำลังทำ").length;
  const pending = tasks.filter((task) => task.status === "รอดำเนินการ").length;
  const issueTasks = tasks.filter((task) => task.status === "มีปัญหา").length;
  useEffect(() => {
    const timer = window.setInterval(() => setSyncTime(new Date()), 60000);
    return () => window.clearInterval(timer);
  }, []);
  useEffect(() => {
    let isActive = true;
    const client = getSupabaseClient({ silent: true });
    const fallbackUser = authProfile ? [{
      id: authProfile.id || authProfile.email,
      name: profileDisplayName(authProfile),
      email: authProfile.email || "",
      role: roleInfo(role).label,
      activity: `กำลังดู Dashboard / ${roleInfo(role).label}`,
      page: "dashboard",
      lastSeen: new Date().toISOString(),
    }] : [];
    const loadPresence = async () => {
      if (!client || !canUseBackendPresence(role)) {
        if (isActive) {
          setActiveUsers(fallbackUser);
          setPresenceStatus(client ? "restricted" : "mock");
        }
        return;
      }
      try {
        const { data, error } = await client
          .from("user_presence")
          .select("user_id,email,full_name,role,current_page,last_seen_at,status,updated_at,created_at")
          .eq("status", "online")
          .gte("last_seen_at", activePresenceCutoff(2))
          .order("last_seen_at", { ascending: false });
        if (error) throw error;
        if (!isActive) return;
        const rows = (data || []).map(normalizePresenceRow);
        setActiveUsers(rows.length ? rows : fallbackUser);
        setPresenceStatus("live");
      } catch (error) {
        console.warn("GoodSeed active users realtime load failed", error);
        if (isActive) {
          setActiveUsers(fallbackUser);
          setPresenceStatus("setup-needed");
        }
      }
    };
    loadPresence();
    if (!client || !canUseBackendPresence(role)) return () => { isActive = false; };
    const channel = client
      .channel("goodseed-user-presence-dashboard")
      .on("postgres_changes", { event: "*", schema: "public", table: "user_presence" }, loadPresence)
      .subscribe();
    const timer = window.setInterval(loadPresence, 30000);
    return () => {
      isActive = false;
      window.clearInterval(timer);
      client.removeChannel?.(channel);
    };
  }, [authProfile?.id, authProfile?.email, role]);
  useEffect(() => {
    let isActive = true;
    if (!isOwnerRole(role)) {
      setPendingAccessCount(0);
      return () => { isActive = false; };
    }
    const client = getSupabaseClient({ silent: true });
    if (!client) return () => { isActive = false; };
    client
      .from("profiles")
      .select("id", { count: "exact", head: true })
      .in("approval_status", ["pending", "pending-approval", "pending-review"])
      .neq("requested_role", "customer")
      .then(({ count, error }) => {
        if (!isActive || error) return;
        setPendingAccessCount(count || 0);
      });
    return () => { isActive = false; };
  }, [role]);
  const smartDetails = {
    trees: { title: "Tree Management", subtitle: "รายละเอียดต้นไม้ทั้งหมด เปิดดูข้อมูลลึกจากหน้า Tree Management", href: "#tree-management", items: [{ label: "จำนวนต้นไม้ปัจจุบัน", value: "3,354 ต้น", note: "รอบปลูก A-C" }, { label: "เป้าหมายหลังขยาย", value: "6,942 ต้น", note: "รวมรอบปลูก D-F" }, { label: "ข้อมูลที่จะเห็นในหน้า Detail", value: "Tree ID / อายุ / โซน / QR / ประวัติ", note: "โหลดเมื่อเข้า Tree Management" }] },
    tasks: { title: "Task Management", subtitle: "รายการงานทั้งหมด ผู้รับผิดชอบ Deadline และหลักฐาน", href: "#daily-work", items: [{ label: "งานค้าง", value: "23 งาน", note: "รอดำเนินการและต้องติดตาม" }, { label: "กำลังทำ", value: `${doing} งาน`, note: "จากข้อมูลตัวอย่างวันนี้" }, { label: "มีปัญหา", value: `${issueTasks} งาน`, note: "ควรตรวจสอบจากหน้าตารางงาน" }] },
    alerts: { title: "Notification Center", subtitle: "แจ้งเตือนย้อนหลัง Filter Priority และผู้รับผิดชอบ", href: "#alerts", items: alerts.map((alert) => ({ label: alert.level, value: alert.title, note: alert.detail })) },
    team: { title: "Team Monitoring", subtitle: presenceStatus === "live" ? "สถานะทีมออนไลน์จาก Supabase Realtime และ last_seen จริง" : "กำลังใช้ข้อมูล session ปัจจุบันจนกว่าจะรัน supabase/user_presence.sql", href: "#people-hr", items: activeUsers.length ? activeUsers.map((user) => ({ label: user.role, value: user.name, note: user.email || user.activity })) : [{ label: "ออนไลน์", value: "0 คน", note: "ยังไม่มี session ที่ล็อกอิน" }] },
    reports: { title: "Manager Reports", subtitle: "รายงานตรวจแปลงและข้อมูล QR ล่าสุด", href: "#daily-report", items: [{ label: "รายงานวันนี้", value: `${todayReportCount} ฉบับ`, note: `ล่าสุดโดย ${latestReport.reporter}` }, { label: "ปัญหาจาก QR", value: latestReport.qrIssue || "ไม่พบปัญหา", note: latestReport.treeId || latestReport.area }, { label: "รูปประกอบ", value: latestReport.photos, note: latestReport.summaryPhoto }] },
    rd: { title: "Experiment & R&D", subtitle: "สรุปสั้นจากงานทดลองทั้งหมด กดเข้าเมนูเพื่อดูหน้าเต็ม", href: "#experiment-rd", items: [{ label: "จำนวนการทดลองทั้งหมด", value: `${rdSummary.total} รายการ`, note: "รองรับการทดลองหลายประเภท ไม่จำกัดแค่มันญี่ปุ่น" }, { label: "กำลังดำเนินการ", value: `${rdSummary.active} รายการ`, note: "รายการที่ยังติดตามผลอยู่" }, { label: "ผลทดลองล่าสุด", value: rdSummary.latestResult, note: `ปัญหาที่พบ: ${rdSummary.issueText}` }] },
  };
  const kpis = [
    { label: "แปลงทั้งหมด", value: "42", unit: "แปลง", hint: "เพิ่มขึ้น 3 จากเดือนก่อน", icon: "map", tone: "bg-goodseed-100 text-goodseed-800", href: "#plots" },
    { label: "ต้นไม้ทั้งหมด", value: "3,354", unit: "ต้น", hint: "รอบปลูก A-C / กดดู Tree Management", icon: "tree", tone: "bg-green-100 text-green-800", onOpen: () => setDetail(smartDetails.trees) },
    { label: "งานเสร็จแล้ว", value: "128", unit: "งาน", hint: "เดือนนี้ / Overview only", icon: "check", tone: "bg-blue-100 text-blue-700", href: "#daily-work" },
    { label: "งานค้าง", value: "23", unit: "งาน", hint: "กดดู Task Management", icon: "calendar", tone: "bg-amber-100 text-amber-800", onOpen: () => setDetail(smartDetails.tasks) },
    { label: "ผลการทดลอง", value: rdSummary.total, unit: "การทดลอง", hint: `กำลังดำเนินการ ${rdSummary.active} / กดเปิด R&D`, icon: "wrench", tone: "bg-violet-100 text-violet-700", href: "#experiment-rd" },
    { label: "ปัญหาสำคัญ", value: "3", unit: "รายการ", hint: "แสดงล่าสุด 3-5 รายการ", icon: "bell", tone: "bg-red-100 text-red-700", onOpen: () => setDetail(smartDetails.alerts) },
  ];

  return (
    <section id="dashboard" className="print-area space-y-4">
      <SmartFarmDetailModal detail={detail} onClose={() => setDetail(null)} />
      <div className="flex flex-col gap-3 rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft lg:flex-row lg:items-center lg:justify-between">
        <div>
          <p className="text-sm font-extrabold text-goodseed-600">หน้าหลัก / Smart Farm Control Center</p>
          <h2 className="text-2xl font-black leading-tight text-goodseed-950 sm:text-3xl">สวัสดีครับ, {currentUserName}</h2>
          <p className="mt-1 text-sm font-semibold text-goodseed-700">ภาพรวมทั้งฟาร์มแบบ Real-time แสดงเฉพาะข้อมูลสำคัญ กดแต่ละ Widget เพื่อดูรายละเอียด</p>
        </div>
        <div className="grid gap-2 sm:grid-cols-3">
          <div className="rounded-lg bg-goodseed-50 px-4 py-3"><p className="text-xs font-bold text-goodseed-600">Weather</p><p className="text-lg font-black text-goodseed-950">{Math.round(dashboardWeather.temperature)}°C</p></div>
          <div className="rounded-lg bg-goodseed-50 px-4 py-3"><p className="text-xs font-bold text-goodseed-600">Sync</p><p className="text-lg font-black text-goodseed-950">{syncLabel} น.</p></div>
          <button onClick={() => setDetail(smartDetails.team)} className="rounded-lg bg-goodseed-700 px-4 py-3 text-left text-white"><p className="text-xs font-bold text-goodseed-100">Active Users</p><p className="text-lg font-black">{activeUsers.length} คน</p><p className="mt-1 text-[10px] font-bold text-goodseed-100">{presenceStatus === "live" ? "Supabase Realtime" : "Session fallback"}</p></button>
        </div>
      </div>

      {isOwnerRole(role) && pendingAccessCount > 0 && (
        <a href="#user-management" className="flex flex-col gap-3 rounded-lg border border-amber-200 bg-amber-50 p-4 text-amber-900 shadow-soft sm:flex-row sm:items-center sm:justify-between">
          <div>
            <p className="text-sm font-black">มีคำขอเข้าใช้งาน Backend รออนุมัติ</p>
            <p className="mt-1 text-sm font-bold">มีผู้สมัครใหม่ {pendingAccessCount} รายการ กรุณาเปิด User Management เพื่ออนุมัติหรือปฏิเสธสิทธิ์</p>
          </div>
          <span className="inline-flex min-h-11 items-center justify-center rounded-lg bg-amber-600 px-4 py-2 text-sm font-black text-white">ไปหน้าอนุมัติ</span>
        </a>
      )}

      <div className={`grid gap-3 ${viewMode === "mobile" ? "grid-cols-1" : viewMode === "tablet" ? "grid-cols-2" : "xl:grid-cols-6"}`}>
        {kpis.map((kpi) => <ControlCard key={kpi.label} {...kpi} />)}
      </div>

      <div className={`grid gap-4 ${viewMode === "desktop" ? "xl:grid-cols-12" : viewMode === "tablet" ? "grid-cols-2" : "grid-cols-1"}`}>
        <ControlWidget title="ภาพรวมฟาร์ม" className="xl:col-span-5" onOpen={() => setDetail({ title: "Farm Overview", subtitle: "พื้นที่ปลูก แหล่งน้ำ โรงเรือน และแผนขยาย", href: "#plots", items: [{ label: "แปลงทั้งหมด", value: "42 แปลง", note: "แสดงเฉพาะภาพรวมบน Dashboard" }, { label: "พื้นที่ไม้ล้อม", value: "30 ไร่", note: "รอบปลูก A-C" }, { label: "พื้นที่เกษตรผสมผสาน", value: "12 ไร่", note: "โครงข่ายกระจายน้ำและพืชเสริม" }] })}>
          <div className="relative overflow-hidden rounded-lg">
            <img src={farmMapImages[0].src} alt="ภาพรวมฟาร์ม GoodSeed" className="h-64 w-full object-cover" />
            <div className="absolute inset-x-3 bottom-3 grid gap-2 sm:grid-cols-3">
              {[["แปลงปลูก", "32 แปลง", "map"], ["บ่อ / แหล่งน้ำ", "4 บ่อ", "leaf"], ["โรงเรือน", "3 หลัง", "building"]].map(([label, value, icon]) => (
                <div key={label} className="rounded-lg bg-goodseed-900/85 p-3 text-white backdrop-blur">
                  <Icon name={icon} className="mb-2 h-5 w-5" /><p className="text-xs font-bold">{label}</p><p className="text-lg font-black">{value}</p>
                </div>
              ))}
            </div>
          </div>
        </ControlWidget>

        <ControlWidget title="รายงานการตรวจแปลงวันนี้" className="xl:col-span-4" action={<a href="#owner-review" className="text-sm font-black text-goodseed-700">ดูรายงาน</a>} onOpen={() => setDetail(smartDetails.reports)}>
          <MiniDonut center="42" label="แปลง" />
          <a href="#owner-review" className="mt-4 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-goodseed-50 px-4 py-2 text-sm font-black text-goodseed-800 hover:bg-goodseed-100"><Icon name="file" />ดูรายงานการตรวจแปลง</a>
        </ControlWidget>

        <ControlWidget title="แจ้งเตือนสำคัญ" className="xl:col-span-3" action={<button onClick={() => setDetail(smartDetails.alerts)} className="text-sm font-black text-goodseed-700">ดูทั้งหมด</button>} onOpen={() => setDetail(smartDetails.alerts)}>
          <div className="space-y-3">
            {alerts.slice(0, 4).map((alert, index) => (
              <button key={alert.title} onClick={() => setDetail(smartDetails.alerts)} className={`flex w-full items-start gap-3 rounded-lg p-3 text-left ${index === 0 ? "bg-red-50" : "bg-amber-50"}`}>
                <Icon name={index === 0 ? "bell" : "leaf"} className={`mt-0.5 h-5 w-5 ${index === 0 ? "text-red-600" : "text-amber-700"}`} />
                <div className="min-w-0 flex-1"><p className={`truncate text-sm font-black ${index === 0 ? "text-red-800" : "text-amber-900"}`}>{alert.title}</p><p className="text-xs font-bold text-slate-600">{alert.detail}</p></div>
              </button>
            ))}
          </div>
        </ControlWidget>

        <ControlWidget title="งานล่าสุด" className="xl:col-span-5" action={<a href="#daily-work" className="text-sm font-black text-goodseed-700">ดูทั้งหมด</a>} onOpen={() => setDetail(smartDetails.tasks)}>
          <DashboardMiniTaskList tasks={tasks} />
        </ControlWidget>

        <ControlWidget title="สรุปรายงานวันนี้" className="xl:col-span-4" action={<a href="#daily-report" className="text-sm font-black text-goodseed-700">บันทึกใหม่</a>} onOpen={() => setDetail(smartDetails.reports)}>
          <div className="grid gap-3 sm:grid-cols-2">
            <MiniMetric label="ต้นไม้ปกติ" value={`${latestReport.normal.toLocaleString("th-TH")} ต้น`} />
            <MiniMetric label="ต้นไม้ผิดปกติ" value={`${latestReport.abnormal} ต้น`} danger />
            <MiniMetric label="ให้น้ำแล้ว" value="3 แปลง" />
            <MiniMetric label="รูปถ่าย" value="18 รูป" />
          </div>
          <p className="mt-3 line-clamp-2 rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800">{latestReport.summary}</p>
        </ControlWidget>

        <ControlWidget title="เมนูด่วน" className="xl:col-span-3">
          <div className="grid grid-cols-2 gap-3">
            {[
              ["เพิ่มงาน", "check", "#daily-work"],
              ["สแกน QR", "qr", "#daily-report"],
              ["รายงานวันนี้", "file", "#daily-report"],
              ["วัสดุคงคลัง", "box", "#inventory"],
              ["ทีมออนไลน์", "users", null],
              ["ปฏิทินงาน", "calendar", "#responsibility"],
            ].map(([label, icon, href]) => href ? (
              <a key={label} href={href} className="grid min-h-[92px] place-items-center rounded-lg border border-goodseed-100 bg-white p-3 text-center font-black text-goodseed-800 transition hover:bg-goodseed-50"><Icon name={icon} className="mb-2 h-7 w-7" />{label}</a>
            ) : (
              <button key={label} onClick={() => setDetail(smartDetails.team)} className="grid min-h-[92px] place-items-center rounded-lg border border-goodseed-100 bg-white p-3 text-center font-black text-goodseed-800 transition hover:bg-goodseed-50"><Icon name={icon} className="mb-2 h-7 w-7" />{label}</button>
            ))}
          </div>
        </ControlWidget>

        <ControlWidget title="กราฟสรุปงาน (เดือนนี้)" className="xl:col-span-3" onOpen={() => setDetail(smartDetails.tasks)}>
          <DonutChart />
          <a href="#daily-work" className="mt-3 inline-flex w-full items-center justify-center rounded-lg bg-goodseed-50 px-4 py-2 text-sm font-black text-goodseed-800">ดูงานทั้งหมด</a>
        </ControlWidget>

        <ControlWidget title="Experiment & R&D" className="xl:col-span-3" action={<a href="#experiment-rd" className="text-sm font-black text-goodseed-700">เปิดหน้าเต็ม</a>} onOpen={() => setDetail(smartDetails.rd)}>
          <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-1">
            <MiniMetric label="จำนวนการทดลองทั้งหมด" value={`${rdSummary.total} รายการ`} />
            <MiniMetric label="การทดลองที่กำลังดำเนินการ" value={`${rdSummary.active} รายการ`} />
            <MiniMetric label="ผลทดลองล่าสุด" value={rdSummary.latestResult} />
            <MiniMetric label="ปัญหาที่พบ" value={rdSummary.issueText} danger={rdSummary.issues > 0} />
          </div>
          <a href="#experiment-rd" className="mt-3 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-black text-white">
            <Icon name="leaf" className="h-4 w-4" />เปิด Experiment & R&D
          </a>
        </ControlWidget>

        <ControlWidget title="ภาพจากแปลงวันนี้" className="xl:col-span-6" action={<a href="#owner-review" className="text-sm font-black text-goodseed-700">ดูทั้งหมด</a>}>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
            {[farmMapImages[1].src, farmMapImages[2].src, farmMapImages[3].src, aboutImages.treesLandscape].map((src, index) => (
              <a key={src} href="#owner-review" className="relative overflow-hidden rounded-lg">
                <img src={src} alt={`ภาพจากแปลง ${index + 1}`} className="h-36 w-full object-cover transition hover:scale-105" />
                {index === 3 && <div className="absolute inset-0 grid place-items-center bg-goodseed-950/55 text-center text-xl font-black text-white">+15<br /><span className="text-sm">รูปเพิ่มเติม</span></div>}
              </a>
            ))}
          </div>
        </ControlWidget>
      </div>

      <div className="rounded-lg border border-goodseed-100 bg-gradient-to-r from-goodseed-50 to-white p-4 shadow-soft">
        <div className="grid gap-3 lg:grid-cols-[1fr_repeat(4,170px)_2fr] lg:items-center">
          <p className="text-lg font-black text-goodseed-950">Download Center</p>
          {["PDF", "Excel", "Word", "รูปภาพ (ZIP)"].map((label) => (
            <button key={label} onClick={() => downloadFile(`goodseed-control-center-${label}.txt`, `GoodSeed Farm Smart Farm Control Center\n${label}`, "text/plain;charset=utf-8")} className="rounded-lg bg-white px-4 py-3 text-sm font-black text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-50">
              <Icon name="download" className="mr-2 inline h-5 w-5" />{label}
            </button>
          ))}
          <button onClick={() => downloadFile("goodseed-summary-report.pdf.txt", "Generate PDF mock: Smart Farm Control Center", "text/plain;charset=utf-8")} className="rounded-lg bg-goodseed-700 px-5 py-3 text-center text-lg font-black text-white shadow-soft transition hover:bg-goodseed-800">
            <Icon name="download" className="mr-2 inline h-6 w-6" />สร้างรายงานสรุป (PDF)
          </button>
        </div>
      </div>
    </section>
  );
}

function DailyReportCenter({ role }) {
  const [reportRows, setReportRows] = useState([]);
  const [notificationRows, setNotificationRows] = useState([]);
  const [filters, setFilters] = useState({ date: "", plantingRound: "ทั้งหมด", irrigationZone: "ทั้งหมด", employee: "", status: "ทั้งหมด" });
  const [status, setStatus] = useState("loading");
  const canReview = isOwnerRole(role) || ["admin", "manager", "developer"].includes(role);
  const loadReportCenter = async () => {
    const client = getSupabaseClient({ silent: true });
    if (!client || !canReview) {
      setStatus("missing");
      return;
    }
    try {
      let reportQuery = client.from("daily_reports").select("*").order("updated_at", { ascending: false }).limit(80);
      if (filters.date) reportQuery = reportQuery.eq("report_date", filters.date);
      if (filters.plantingRound !== "ทั้งหมด") reportQuery = reportQuery.eq("planting_round", filters.plantingRound);
      if (filters.irrigationZone !== "ทั้งหมด") reportQuery = reportQuery.eq("irrigation_zone", Number(filters.irrigationZone));
      if (filters.status !== "ทั้งหมด") reportQuery = reportQuery.eq("status", filters.status);
      if (filters.employee.trim()) reportQuery = reportQuery.ilike("employee_name", `%${filters.employee.trim()}%`);
      const [{ data: reportsData, error: reportsError }, { data: notificationsData, error: notificationsError }] = await Promise.all([
        reportQuery,
        client.from("notifications").select("*").eq("type", "daily_report_submitted").order("created_at", { ascending: false }).limit(20),
      ]);
      if (reportsError || notificationsError) throw reportsError || notificationsError;
      setReportRows(reportsData || []);
      setNotificationRows(notificationsData || []);
      setStatus("ready");
    } catch (error) {
      console.warn("GoodSeed Report Center load failed", error);
      setStatus("error");
    }
  };
  useEffect(() => {
    loadReportCenter();
  }, [role, filters.date, filters.plantingRound, filters.irrigationZone, filters.employee, filters.status]);
  useEffect(() => {
    const client = getSupabaseClient({ silent: true });
    if (!client || !canReview) return undefined;
    const channel = client
      .channel("goodseed-daily-report-center")
      .on("postgres_changes", { event: "*", schema: "public", table: "daily_reports" }, loadReportCenter)
      .on("postgres_changes", { event: "*", schema: "public", table: "notifications" }, loadReportCenter)
      .subscribe();
    return () => { client.removeChannel(channel); };
  }, [role, canReview]);
  const updateReportStatus = async (reportId, nextStatus) => {
    const client = getSupabaseClient({ silent: true });
    if (!client) return;
    const { data: userData } = await client.auth.getUser();
    const { error } = await client.from("daily_reports").update({
      status: nextStatus,
      reviewed_by: userData?.user?.id || null,
      reviewed_at: ["approved", "need_revision", "rejected", "under_review"].includes(nextStatus) ? new Date().toISOString() : null,
      updated_by: userData?.user?.id || null,
    }).eq("id", reportId);
    if (!error) loadReportCenter();
  };
  const today = todayInputValue();
  const counts = {
    today: reportRows.filter((report) => report.report_date === today).length,
    pendingReview: reportRows.filter((report) => ["submitted", "under_review"].includes(report.status)).length,
    approved: reportRows.filter((report) => report.status === "approved").length,
    needRevision: reportRows.filter((report) => report.status === "need_revision").length,
    history: reportRows.length,
    unread: notificationRows.filter((notification) => notification.status === "unread").length,
  };
  if (!canReview) return null;
  return (
    <DashboardPanel title="Report Center" action={<Badge className="bg-amber-50 text-amber-800 ring-amber-100">{counts.unread} unread notification</Badge>}>
      {status === "error" && <p className="mb-4 rounded-xl bg-amber-50 p-3 text-sm font-bold text-amber-900">ยังโหลด Report Center ไม่ได้ กรุณารัน supabase/daily_report_schedule.sql เวอร์ชันล่าสุดใน Supabase SQL Editor</p>}
      <div className="grid gap-3 md:grid-cols-5">
        {[["รายงานวันนี้", counts.today], ["รายงานรอตรวจ", counts.pendingReview], ["อนุมัติแล้ว", counts.approved], ["ต้องแก้ไข", counts.needRevision], ["รายงานย้อนหลัง", counts.history]].map(([label, value]) => (
          <div key={label} className="rounded-xl bg-goodseed-50 p-3">
            <p className="text-xs font-black text-goodseed-600">{label}</p>
            <p className="mt-1 text-2xl font-black text-goodseed-950">{value}</p>
          </div>
        ))}
      </div>
      <div className="mt-4 grid gap-3 lg:grid-cols-5">
        <Input label="วันที่" type="date" value={filters.date} onChange={(value) => setFilters((current) => ({ ...current, date: value }))} />
        <Select label="รอบปลูก" value={filters.plantingRound} onChange={(value) => setFilters((current) => ({ ...current, plantingRound: value }))} options={["ทั้งหมด", "A", "B", "C", "D", "E", "F"]} />
        <Select label="โซนน้ำ" value={filters.irrigationZone} onChange={(value) => setFilters((current) => ({ ...current, irrigationZone: value }))} options={["ทั้งหมด", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]} />
        <Input label="ชื่อพนักงาน" value={filters.employee} onChange={(value) => setFilters((current) => ({ ...current, employee: value }))} />
        <Select label="สถานะ" value={filters.status} onChange={(value) => setFilters((current) => ({ ...current, status: value }))} options={["ทั้งหมด", ...dailyReportStatusOptions]} />
      </div>
      <div className="mt-4 thin-scrollbar overflow-x-auto">
        <table className="min-w-[1120px] w-full text-left text-sm">
          <thead className="bg-goodseed-50 text-goodseed-800">
            <tr>{["Report ID", "Employee", "Role", "รอบปลูก", "โซนน้ำ", "Report Date", "Submit DateTime", "Status", "Review"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr>
          </thead>
          <tbody className="divide-y divide-goodseed-100">
            {reportRows.map((report) => (
              <tr key={report.id} className="align-top">
                <td className="px-3 py-3 font-black text-goodseed-900"><a href="#daily-report" className="hover:underline">{report.report_code || report.id.slice(0, 8)}</a></td>
                <td className="px-3 py-3"><p className="font-black text-goodseed-950">{report.employee_name || "-"}</p><p className="text-xs font-bold text-goodseed-600">{String(report.employee_id || "").slice(0, 8)}</p></td>
                <td className="px-3 py-3 font-bold">{report.employee_role || "-"}</td>
                <td className="px-3 py-3 font-bold">{report.planting_round}</td>
                <td className="px-3 py-3 font-bold">{report.irrigation_zone}</td>
                <td className="px-3 py-3 font-bold">{report.report_date}</td>
                <td className="px-3 py-3 font-bold">{report.submit_datetime ? new Date(report.submit_datetime).toLocaleString("th-TH", { dateStyle: "medium", timeStyle: "short" }) : "-"}</td>
                <td className="px-3 py-3"><Badge className={dailyReportStatusTone(report.status)}>{dailyReportStatusLabels[report.status] || report.status}</Badge></td>
                <td className="px-3 py-3">
                  <select value={report.status || "draft"} onChange={(event) => updateReportStatus(report.id, event.target.value)} className="rounded-lg border border-goodseed-100 bg-white px-3 py-2 text-xs font-bold text-goodseed-900">
                    {dailyReportStatusOptions.map((option) => <option key={option} value={option}>{dailyReportStatusLabels[option]}</option>)}
                  </select>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {reportRows.length === 0 && <p className="mt-4 rounded-xl bg-goodseed-50 p-4 text-sm font-bold text-goodseed-700">ยังไม่มีรายงานตามเงื่อนไขค้นหา</p>}
    </DashboardPanel>
  );
}

function HomeHero() {
  return (
    <section id="home-hero" className="overflow-hidden rounded-lg border border-goodseed-100 bg-goodseed-900 shadow-soft">
      <img src={homeHeroImage} alt="GoodSeed Farm Vision 2030" className="h-auto w-full object-contain" />
    </section>
  );
}

function OrganizationGoals() {
  const [active, setActive] = useState(organizationGoalImages[0]);

  return (
    <section id="organization-goals" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
      <SectionHeader
        title="เป้าหมายองค์กร"
        subtitle="ตัวอย่างผลผลิตและบรรจุภัณฑ์ที่คาดว่าจะเกิดขึ้นในปี 2026"
        action={<Badge className="bg-goodseed-700 text-white ring-goodseed-700">Vision 2026</Badge>}
      />
      <div className="grid gap-5 xl:grid-cols-[1.18fr_0.82fr]">
        <a href={active.src} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-lg border border-goodseed-100 bg-goodseed-50">
          <div className="grid min-h-[280px] place-items-center bg-white p-2 sm:min-h-[420px]">
            <img src={active.src} alt={active.title} className="max-h-[760px] w-full object-contain" />
          </div>
          <div className="border-t border-goodseed-100 bg-white p-4">
            <p className="font-extrabold text-goodseed-900">{active.title}</p>
            <p className="mt-1 text-sm text-goodseed-700">{active.detail}</p>
          </div>
        </a>
        <div className="space-y-3">
          <div className="rounded-lg bg-goodseed-50 p-4 ring-1 ring-goodseed-100">
            <p className="font-extrabold text-goodseed-900">เป้าหมายผลิตภัณฑ์ปี 2026</p>
            <p className="mt-2 text-sm text-goodseed-700">สร้างรายได้จากวัสดุหมุนเวียนในฟาร์ม เช่น ไบโอชา น้ำส้มควันไม้ แหนแดง ถั่วบราซิล มันญี่ปุ่น และชุดเกษตรยั่งยืน</p>
          </div>
          <div className="thin-scrollbar grid max-h-[720px] gap-3 overflow-y-auto pr-1 sm:grid-cols-2 xl:grid-cols-1">
            {organizationGoalImages.map((item) => (
              <button
                key={item.src}
                onClick={() => setActive(item)}
                className={`flex gap-3 rounded-lg border p-3 text-left transition ${
                  active.src === item.src ? "border-goodseed-600 bg-goodseed-50" : "border-goodseed-100 bg-white hover:bg-goodseed-50"
                }`}
              >
                <img src={item.src} alt={item.title} className="h-20 w-28 shrink-0 rounded-md object-cover" />
                <div className="min-w-0">
                  <p className="font-extrabold text-goodseed-900">{item.title}</p>
                  <p className="mt-1 line-clamp-2 text-xs text-goodseed-700">{item.detail}</p>
                </div>
              </button>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function ContentManagementActions({ role }) {
  if (!["owner", "admin", "manager"].includes(role)) return null;
  return (
    <div className="flex flex-wrap gap-2">
      {["เพิ่มข่าวสาร", "แก้ไข", "ลบ", "เผยแพร่ / ซ่อน", "เพิ่มรูปภาพ", "เพิ่มลิงก์", "ตั้งวันที่เผยแพร่"].map((label) => (
        <button key={label} className="rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-xs font-extrabold leading-5 text-goodseed-800 shadow-sm hover:bg-goodseed-50">{label}</button>
      ))}
    </div>
  );
}

function NewsPromotionPage({ role }) {
  const editable = ["owner", "admin", "manager"].includes(role);
  return (
    <section id="news-promotion" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
      <SectionHeader
        title={<BiLabel th="ข่าวสารและโปรโมชั่น" en="News & Promotion" />}
        subtitle="พื้นที่สำหรับเพิ่ม อัปเดต และเผยแพร่ข่าวสารฟาร์ม โปรโมชั่นสินค้า สินค้าใหม่ ผลผลิตพร้อมขาย กิจกรรม ประกาศลูกค้า และบทความความรู้ด้านเกษตร"
        action={editable ? <ContentManagementActions role={role} /> : <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">ข้อมูลเผยแพร่ Public</Badge>}
      />
      <div className="grid gap-5 lg:grid-cols-3">
        {newsPromotionItems.filter((item) => editable || item.status === "เผยแพร่").map((item) => (
          <article key={item.title} className="overflow-hidden rounded-lg border border-goodseed-100 bg-goodseed-50 shadow-sm">
            <div className="grid h-48 place-items-center bg-white p-2">
              <img src={item.image} alt={item.title} className="max-h-full w-full rounded-md object-cover" />
            </div>
            <div className="space-y-3 p-4">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{item.type}</Badge>
                <Badge className={item.status === "เผยแพร่" ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : "bg-slate-100 text-slate-600 ring-slate-200"}>{item.status}</Badge>
              </div>
              <div>
                <h3 className="text-lg font-extrabold leading-snug text-goodseed-950">{item.title}</h3>
                <p className="mt-1 text-xs font-bold text-goodseed-600">วันที่เผยแพร่: {item.date}</p>
              </div>
              <p className="text-sm font-semibold leading-7 text-goodseed-700">{item.summary}</p>
              <div className="flex flex-wrap gap-2 pt-1">
                <a href={item.link} className="rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white">เปิดอ่าน</a>
                {editable && <button className="rounded-lg bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-100">แก้ไขเนื้อหา</button>}
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

function CompanyProfilePage({ role }) {
  const editable = ["owner", "admin", "manager"].includes(role);
  return (
    <section id="company-profile" className="space-y-6">
      <div className="overflow-hidden rounded-lg border border-goodseed-100 bg-goodseed-950 shadow-soft">
        <div className="relative min-h-[520px]">
          <img src={aboutImages.hero} alt="GOODSEED Farm" className="absolute inset-0 h-full w-full object-cover" />
          <div className="absolute inset-0 bg-gradient-to-r from-goodseed-950/85 via-goodseed-950/45 to-transparent" />
          <div className="relative z-10 flex min-h-[520px] flex-col justify-end p-6 text-white sm:p-10 lg:p-14">
            <Badge className="mb-5 w-fit bg-white/15 text-white ring-white/20">About Us / Company Profile</Badge>
            <h1 className="max-w-4xl text-5xl font-black leading-tight tracking-normal sm:text-6xl lg:text-7xl">GOODSEED FARM</h1>
            <p className="mt-5 max-w-3xl text-xl font-bold leading-9 text-goodseed-50 sm:text-2xl">ฟาร์มไม้ล้อมและเกษตรผสมผสานสมัยใหม่ เพื่อเกษตรยั่งยืน</p>
            <div className="mt-8 flex flex-wrap gap-3">
              {["Premium Nursery", "Modern Farm", "Sustainable Agriculture"].map((item) => (
                <span key={item} className="rounded-full bg-white/15 px-4 py-2 text-sm font-extrabold text-white ring-1 ring-white/20">{item}</span>
              ))}
            </div>
          </div>
        </div>
      </div>

      <section className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6 lg:p-8">
        <SectionHeader
          title={<BiLabel th="เกี่ยวกับเรา" en="About Us" />}
          subtitle="ตัวตนของฟาร์มไม้ล้อมที่เริ่มจากการวางระบบจริงในพื้นที่จริง"
          action={editable ? <div className="flex flex-wrap gap-2"><button className="rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white">แก้ไขข้อมูล</button><button className="rounded-lg border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800">เพิ่มรูปภาพ</button></div> : <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Published Profile</Badge>}
        />
        <div className="grid gap-6 lg:grid-cols-[0.9fr_1.1fr]">
          <div className="overflow-hidden rounded-lg border border-goodseed-100 bg-[#fbf8ef]">
            <img src={aboutImages.owner} alt="เจ้าของฟาร์ม GoodSeed ในทุ่งดอกทานตะวัน" className="h-full min-h-[320px] w-full object-cover" />
          </div>
          <div className="flex flex-col justify-center rounded-lg bg-goodseed-50 p-6">
            <p className="text-lg font-bold leading-9 text-goodseed-900">
              GOODSEED Farm คือฟาร์มไม้ล้อมและเกษตรผสมผสาน ตั้งอยู่ที่อำเภอโคกเจริญ จังหวัดลพบุรี เริ่มต้นในปี 2026 มุ่งเน้นการพัฒนาไม้ล้อมคุณภาพสูง ควบคู่กับการจัดการดิน น้ำ และระบบรากอย่างเป็นระบบ
            </p>
            <div className="mt-6 grid gap-3 sm:grid-cols-3">
              <MiniMetric label="พื้นที่ดำเนินงาน" value="42 ไร่" />
              <MiniMetric label="พื้นที่ไม้ล้อมเชิงพาณิชย์" value="30 ไร่" />
              <MiniMetric label="เกษตรผสมผสาน" value="12 ไร่" />
            </div>
          </div>
        </div>
      </section>

      <section className="grid gap-6 xl:grid-cols-[0.95fr_1.05fr]">
        <div className="overflow-hidden rounded-lg border border-goodseed-100 bg-white shadow-soft">
          <img src={aboutImages.vision} alt="วิสัยทัศน์และภารกิจของ GoodSeed Farm" className="h-full min-h-[360px] w-full object-cover" />
        </div>
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-1">
          {[
            { title: "วิสัยทัศน์", en: "Vision", icon: "leaf", text: "สร้างฟาร์มไม้ล้อมมาตรฐานสูง ควบคู่กับเกษตรยั่งยืน ฟื้นฟูดิน และใช้ทรัพยากรในฟาร์มให้เกิดประโยชน์สูงสุด" },
            { title: "ภารกิจ", en: "Mission", icon: "check", text: "ปลูกและดูแลไม้ล้อมให้ได้คุณภาพ ส่งมอบข้อมูลตรวจสอบย้อนกลับ พัฒนาระบบ QR และยกระดับฟาร์มสู่ตลาดในประเทศและส่งออก" },
          ].map((item) => (
            <article key={item.title} className="rounded-lg border border-goodseed-100 bg-white p-6 shadow-soft">
              <div className="mb-5 grid h-14 w-14 place-items-center rounded-lg bg-goodseed-100 text-goodseed-800">
                <Icon name={item.icon} className="h-7 w-7" />
              </div>
              <h2 className="text-2xl font-black text-goodseed-950">{item.title}</h2>
              <p className="mt-1 text-sm font-extrabold uppercase tracking-normal text-goodseed-600">{item.en}</p>
              <p className="mt-4 text-base font-semibold leading-8 text-goodseed-700">{item.text}</p>
            </article>
          ))}
        </div>
      </section>

      <section className="rounded-lg border border-goodseed-100 bg-goodseed-950 p-4 text-white shadow-soft sm:p-6 lg:p-8">
        <SectionHeader
          title={<span className="text-white">ผังรวมแปลงและรอบปลูก</span>}
          subtitle={<span className="text-goodseed-100">Master Plan / Blueprint ของฟาร์มจริง รองจาก Hero ส่วนนี้คือหลักฐานระบบการปลูกและการบริหารพื้นที่</span>}
          action={<Badge className="bg-white/15 text-white ring-white/20">Farm Master Plan</Badge>}
        />
        <p className="mb-6 max-w-4xl text-base font-semibold leading-8 text-goodseed-50">
          ฟาร์มของเราวางผังการปลูกเป็นรอบและโซนอย่างชัดเจน เพื่อให้สามารถบริหารจัดการ ตรวจสอบ และขยายกำลังการผลิตได้อย่างเป็นระบบ
        </p>
        <div className="grid gap-5 xl:grid-cols-3">
          {aboutMasterPlans.map((plan) => (
            <article key={plan.title} className="overflow-hidden rounded-lg bg-white text-goodseed-950 shadow-soft">
              <div className={`h-2 ${plan.accent}`} />
              <div className="grid min-h-[260px] place-items-center bg-white p-2">
                <img src={plan.image} alt={plan.title} className="max-h-[360px] w-full rounded-md object-contain" />
              </div>
              <div className="space-y-4 border-t border-goodseed-100 p-5">
                <div>
                  <h3 className="text-2xl font-black">{plan.title}</h3>
                  <p className="text-sm font-bold text-goodseed-600">Planting Round / Blueprint Zone</p>
                </div>
                <div className="grid grid-cols-3 gap-2">
                  <MiniMetric label="พื้นที่" value={plan.area} />
                  <MiniMetric label="แถว" value={plan.code} />
                  <MiniMetric label="รวม" value={plan.total} />
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>

      <section className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6 lg:p-8">
        <SectionHeader
          title={<BiLabel th="ไม้ล้อมคุณภาพจาก GOODSEED Farm" en="Main Product / Premium Landscape Trees" />}
          subtitle="สินค้าหลักของฟาร์มคือไม้ล้อม ระบบการปลูก การดูแล และการตรวจสอบจึงถูกออกแบบมาเพื่อคุณภาพของต้นไม้เป็นอันดับแรก"
          action={<Badge className="bg-goodseed-700 text-white ring-goodseed-700">สินค้าหลักของฟาร์ม</Badge>}
        />
        <div className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
          <div className="grid gap-4 md:grid-cols-2">
            {[aboutImages.treesLandscape, aboutImages.forestTrees].map((src, index) => (
              <div key={src} className="overflow-hidden rounded-lg border border-goodseed-100 bg-goodseed-50">
                <img src={src} alt={index === 0 ? "หมวดไม้ล้อม" : "ไม้ป่าและไม้เศรษฐกิจ"} className="h-full min-h-[360px] w-full object-cover" />
              </div>
            ))}
          </div>
          <div className="rounded-lg bg-goodseed-50 p-6">
            <p className="text-lg font-bold leading-9 text-goodseed-900">
              เราคัดเลือกและดูแลไม้ล้อมตั้งแต่ระยะเริ่มต้น เพื่อให้ได้ต้นไม้ที่แข็งแรง ระบบรากดี ลำต้นสมบูรณ์ และพร้อมสำหรับงานภูมิทัศน์ โครงการจัดสวน และการพัฒนาสู่ตลาดส่งออกในอนาคต
            </p>
            <div className="mt-6 flex flex-wrap gap-2">
              {landscapeTreeTypes.map((tree) => (
                <span key={tree} className="rounded-full bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800 ring-1 ring-goodseed-100">{tree}</span>
              ))}
            </div>
            <div className="mt-6 grid gap-3 sm:grid-cols-3">
              <MiniMetric label="ระบบราก" value="แข็งแรง" />
              <MiniMetric label="มาตรฐาน" value="พร้อมตรวจ" />
              <MiniMetric label="ตลาดเป้าหมาย" value="ในประเทศ / ส่งออก" />
            </div>
          </div>
        </div>
      </section>

      <section className="grid gap-6 xl:grid-cols-[0.9fr_1.1fr]">
        <div className="rounded-lg border border-goodseed-100 bg-white p-6 shadow-soft">
          <SectionHeader
            title={<BiLabel th="เกษตรยั่งยืน" en="Sustainable Farming" />}
            subtitle="ฟื้นฟูดิน ลดสารเคมี และใช้ระบบน้ำเพื่อให้ฟาร์มเติบโตอย่างมั่นคง"
          />
          <p className="text-base font-semibold leading-8 text-goodseed-700">
            GOODSEED Farm ให้ความสำคัญกับการฟื้นฟูดิน ลดการใช้สารเคมี ใช้ระบบน้ำ โครงข่ายกระจายน้ำภายในฟาร์ม พืชคลุมดิน และการจัดการฟาร์มแบบยั่งยืน เพื่อให้การผลิตไม้ล้อมมีคุณภาพทั้งต้นไม้ ดิน น้ำ และระบบนิเวศรอบฟาร์ม
          </p>
          <div className="mt-6 grid gap-3 sm:grid-cols-2">
            {["ลดการใช้สารเคมี", "ฟื้นฟูดินอินทรีย์", "ระบบน้ำและโครงข่ายกระจายน้ำ", "พืชคลุมดินและหมุนเวียนทรัพยากร"].map((item) => (
              <div key={item} className="flex items-center gap-3 rounded-lg bg-goodseed-50 p-3 font-extrabold text-goodseed-800">
                <Icon name="leaf" className="h-5 w-5" />
                {item}
              </div>
            ))}
          </div>
        </div>
        <div className="grid gap-4 md:grid-cols-2">
          {[aboutImages.sustainable, aboutImages.farmGoals].map((src) => (
            <div key={src} className="overflow-hidden rounded-lg border border-goodseed-100 bg-white shadow-soft">
              <img src={src} alt="แนวทางเกษตรยั่งยืนของ GoodSeed Farm" className="h-full min-h-[300px] w-full object-cover" />
            </div>
          ))}
        </div>
      </section>

      <section className="rounded-lg border border-goodseed-100 bg-[#fbf8ef] p-4 shadow-soft sm:p-6 lg:p-8">
        <SectionHeader
          title={<BiLabel th="ผลิตภัณฑ์เสริมจากฟาร์ม" en="Supporting Products" />}
          subtitle="ผลิตภัณฑ์เหล่านี้เป็นส่วนต่อยอดจากทรัพยากรในฟาร์ม เพื่อสนับสนุนระบบไม้ล้อมและเกษตรยั่งยืน ไม่ใช่สินค้าหลักของฟาร์ม"
          action={<Badge className="bg-white text-goodseed-800 ring-goodseed-100">สินค้าเสริม</Badge>}
        />
        <div className="grid gap-5 lg:grid-cols-[0.85fr_1.15fr]">
          <div className="overflow-hidden rounded-lg border border-goodseed-100 bg-white">
            <img src={aboutImages.supportingProducts} alt="ผลิตภัณฑ์เสริมจากฟาร์ม GoodSeed" className="h-auto w-full object-contain" />
          </div>
          <div className="grid content-start gap-3 sm:grid-cols-2">
            {supportingProductNames.map((name) => (
              <div key={name} className="rounded-lg border border-goodseed-100 bg-white p-4">
                <p className="font-extrabold text-goodseed-950">{name}</p>
                <p className="mt-1 text-sm font-semibold leading-6 text-goodseed-700">ผลิตภัณฑ์เสริมจากระบบหมุนเวียนทรัพยากรของฟาร์ม</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="rounded-lg bg-goodseed-950 p-8 text-center text-white shadow-soft">
        <p className="mx-auto max-w-4xl text-2xl font-black leading-10">
          “ต้นไม้ที่แข็งแรง เริ่มต้นจากรากฐานที่ดี และคุณภาพที่แท้จริง ต้องเติบโตอย่างยั่งยืนในทุกขั้นตอน”
        </p>
        <p className="mt-4 text-sm font-bold uppercase tracking-normal text-goodseed-100">GOODSEED Farm</p>
      </section>
    </section>
  );
}

function FarmMapGallery() {
  const [active, setActive] = useState(farmMapImages[0]);

  return (
    <section id="plots" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
      <SectionHeader
        title="ผังรวมแปลงและรอบปลูก"
        subtitle="ใช้รูปต้นฉบับของฟาร์ม: ผังรวม, รอบปลูก A, รอบปลูก B และรอบปลูก C"
        action={<Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">GoodSeed Farm</Badge>}
      />
      <div className="grid gap-5 xl:grid-cols-[1.3fr_0.7fr]">
        <a href={active.src} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-lg border border-goodseed-100 bg-goodseed-50">
          <div className="grid min-h-[280px] place-items-center bg-white p-2 sm:min-h-[420px]">
            <img src={active.src} alt={active.title} className="max-h-[620px] w-full object-contain" />
          </div>
          <div className="border-t border-goodseed-100 bg-white p-4">
            <p className="font-extrabold text-goodseed-900">{active.title}</p>
            <p className="mt-1 text-sm text-goodseed-700">{active.detail}</p>
          </div>
        </a>
        <div className="space-y-3">
          <div className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
            <div className="flex items-center gap-3">
              <img src={farmLogo} alt="GoodSeed Farm logo" className="h-16 w-16 rounded-lg object-cover ring-1 ring-goodseed-200" />
              <div>
                <p className="font-extrabold text-goodseed-900">GoodSeed Farm</p>
                <p className="text-sm text-goodseed-700">ต้นไม้รวมปัจจุบัน 3,354 ต้น จาก 129 แถว</p>
              </div>
            </div>
          </div>
          {farmMapImages.map((item) => (
            <button
              key={item.src}
              onClick={() => setActive(item)}
              className={`flex w-full gap-3 rounded-lg border p-3 text-left transition ${
                active.src === item.src ? "border-goodseed-600 bg-goodseed-50" : "border-goodseed-100 bg-white hover:bg-goodseed-50"
              }`}
            >
              <img src={item.src} alt={item.title} className="h-20 w-28 shrink-0 rounded-md object-cover" />
              <div className="min-w-0">
                <p className="font-extrabold text-goodseed-900">{item.title}</p>
                <p className="mt-1 line-clamp-2 text-xs text-goodseed-700">{item.detail}</p>
              </div>
            </button>
          ))}
        </div>
      </div>
      <PlantingTreeSummary />
    </section>
  );
}

function PlantingTreeSummary() {
  const totalTrees = plantingRoundSummary.reduce((sum, round) => sum + round.total, 0);
  const totalRows = plantingRoundSummary.reduce((sum, round) => sum + round.rows, 0);

  return (
    <div id="trees" className="mt-5 space-y-5">
      <div className="grid gap-4 md:grid-cols-3">
        <MiniMetric label="ต้นไม้รวมตอนนี้" value={`${totalTrees.toLocaleString("th-TH")} ต้น`} />
        <MiniMetric label="จำนวนแถวรวม" value={`${totalRows} แถว`} />
        <MiniMetric label="รอบปลูก" value="A / B / C" />
      </div>
      <div className="grid gap-4 xl:grid-cols-3">
        {plantingRoundSummary.map((round) => (
          <div key={round.round} className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
            <div className="flex items-start justify-between gap-3">
              <div>
                <h3 className="font-extrabold text-goodseed-900">{round.round}</h3>
                <p className="mt-1 text-sm text-goodseed-700">{round.ranges.join(", ")} | {round.rows} แถว</p>
              </div>
              <Badge className="bg-goodseed-700 text-white ring-goodseed-700">{round.total.toLocaleString("th-TH")} ต้น</Badge>
            </div>
            <div className="mt-4 space-y-2">
              {round.species.map((item) => (
                <div key={`${round.round}-${item.name}-${item.rows}`} className="rounded-lg bg-white p-3 ring-1 ring-goodseed-100">
                  <div className="flex items-center justify-between gap-3">
                    <p className="font-bold text-goodseed-900">{item.name}</p>
                    <p className="text-sm font-extrabold text-goodseed-700">{item.count.toLocaleString("th-TH")} ต้น</p>
                  </div>
                  <p className="mt-1 text-xs font-semibold text-goodseed-600">แถว {item.rows}</p>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div className="rounded-lg border border-goodseed-100 bg-white p-4">
        <h3 className="font-extrabold text-goodseed-900">สรุปจำนวนตามชนิดต้นไม้ทั้งหมด</h3>
        <div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {totalTreeBySpecies.map((item) => (
            <div key={item.name} className="flex items-center justify-between gap-3 rounded-lg bg-goodseed-50 px-3 py-2">
              <span className="font-bold text-goodseed-900">{item.name}</span>
              <span className="text-sm font-extrabold text-goodseed-700">{item.count.toLocaleString("th-TH")} ต้น</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ReportForm({ onSave, role = "owner", authProfile, language = "th" }) {
  const [weatherData, setWeatherData] = useState(fallbackWeather);
  const [weatherLoading, setWeatherLoading] = useState(true);
  const [attachmentReport, setAttachmentReport] = useState(null);
  const [ownerSummaryNotice, setOwnerSummaryNotice] = useState("");
  const [ownerSummarySaving, setOwnerSummarySaving] = useState(false);
  const [form, setForm] = useState({
    date: "2026-05-24", reporter: "คุณหวาน", weather: "แดดจัด มีลมอ่อน", area: "แปลง A1", work: "รดน้ำ, ตรวจระบบน้ำ, ตรวจโรคแมลง", issue: "พบเพลี้ยอ่อน 2 จุด", normal: "1232", abnormal: "18", workType: "Tree Inspection", workStatus: "Done", plotId: "A1", rowId: "B17", rowsInspected: "36", treesPlanted: "220", laborCount: "5", hoursWorked: "8", materialUsed: "ปุ๋ย GS-03", materialQty: "12", dailyCost: "6800", progressPercent: "88", growthRate: "8.4", survivalRate: "98.6", photoEvidence: "ภาพงาน 6 รูป", water: "ให้น้ำครบทุกโซน", fertilizer: "ใส่ปุ๋ย GS-03 เสร็จ 78%", disease: "เพลี้ยอ่อนเล็กน้อย", experiment: "ต้นไม้กลุ่มทดลองโตเฉลี่ย +8.4%", photos: "ภาพแปลง 8 รูป", summary: "แปลง A1 โดยรวมปกติ ต้องติดตามเพลี้ยอ่อน", summaryPhoto: "ภาพสรุป 2 รูป", qrType: "QR ต้นไม้", treeId: "TREE-A1-00482", plotZone: "A1 / Zone 1", treeSpecies: "จามจุรีทอง", treeStatus: "ต้องติดตาม", qrIssue: "พบเพลี้ยอ่อนและใบเหลือง", qrPhoto: "ภาพ QR และใบ 3 รูป", qrNote: "ติดตามซ้ำใน 24 ชั่วโมง", soilCondition: "ดินชื้น", standingWater: "ไม่มีน้ำขัง", fieldWeatherNote: "ลมอ่อน เหมาะกับงานตรวจแปลงช่วงเช้า", weatherPhoto: "ภาพสภาพดิน 2 รูป",
  });
  const [saved, setSaved] = useState(false);
  const update = (key, value) => setForm((current) => ({ ...current, [key]: value }));
  const ensureAttachmentReport = async () => {
    const client = getSupabaseClient({ silent: true });
    if (!client) throw new Error("ยังไม่พบ Supabase env จึงอัปโหลดไฟล์จริงไม่ได้");
    const report = await ensureDailyReportForAttachments(client, form, authProfile, role);
    setAttachmentReport(report);
    return { client, report };
  };
  const generateOwnerSummary = () => {
    const lines = [
      `วันที่: ${form.date}`,
      `ผู้รายงาน: ${form.reporter}`,
      `พื้นที่: ${form.area}`,
      `งานวันนี้: ${form.work}`,
      `ปัญหา: ${form.issue || "ไม่มี"}`,
      `สภาพแปลง: ต้นไม้ปกติ ${form.normal} ต้น / ผิดปกติ ${form.abnormal} ต้น`,
    ];
    update("summary", lines.join("\n"));
    setOwnerSummaryNotice("สร้างสรุปเจ้าของฟาร์มจากข้อมูลรายงานแล้ว สามารถแก้ไขข้อความก่อน Submit to Owner ได้");
  };
  const submitAttachmentsToOwner = async () => {
    setOwnerSummarySaving(true);
    setOwnerSummaryNotice("");
    try {
      const { client, report } = await ensureAttachmentReport();
      const { data: userData } = await client.auth.getUser();
      const userId = userData?.user?.id || authProfile?.id;
      const submitTime = new Date().toISOString();
      const { error: reportError } = await client
        .from("daily_reports")
        .update({
          status: "submitted",
          submit_datetime: submitTime,
          submitted_by: userId,
          submitted_name: form.reporter || authProfile?.fullName || authProfile?.email || "",
          submitted_role: roleInfo(role).label || role,
          completed_summary: form.summary || "",
          unfinished_or_problem_summary: form.issue || "",
          updated_by: userId,
        })
        .eq("id", report.id);
      if (reportError) throw reportError;
      await client
        .from("daily_report_attachments")
        .update({ status: "submitted" })
        .eq("report_id", report.id)
        .eq("section_name", "owner-summary");
      await client.from("notifications").insert({
        type: "daily_report_owner_summary",
        title: "Owner Summary Submitted",
        message: `${form.reporter || "พนักงาน"} ส่งสรุปรายงานประจำวันพร้อมไฟล์แนบให้ Owner`,
        target_role: "owner",
        related_table: "daily_reports",
        related_id: report.id,
        payload: { report_id: report.id, report_date: form.date, has_attachments: true, section_name: "owner-summary" },
        created_by: userId,
      });
      setAttachmentReport((current) => ({ ...(current || report), status: "submitted", submit_datetime: submitTime }));
      setOwnerSummaryNotice("ส่งสรุปและไฟล์แนบเข้า Owner Dashboard แล้ว");
    } catch (error) {
      console.warn("GoodSeed owner summary submit failed", error);
      setOwnerSummaryNotice(`ส่งให้ Owner ไม่สำเร็จ: ${supabaseAuthMessage(error)}`);
    } finally {
      setOwnerSummarySaving(false);
    }
  };
  useEffect(() => {
    let active = true;
    const url = `https://api.open-meteo.com/v1/forecast?latitude=${farmWeatherLocation.latitude}&longitude=${farmWeatherLocation.longitude}&current=temperature_2m,relative_humidity_2m,precipitation,rain,cloud_cover,pressure_msl,wind_speed_10m,wind_direction_10m,uv_index&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max,precipitation_sum,uv_index_max&timezone=Asia%2FBangkok`;
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        if (!active) return;
        const current = data.current || {};
        const daily = data.daily || {};
        const forecastRows = (daily.time || []).slice(0, 7).map((date, index) => {
          const rainChance = daily.precipitation_probability_max?.[index] ?? fallbackWeather.rainChance;
          const maxTemp = daily.temperature_2m_max?.[index] ?? fallbackWeather.maxTemp;
          const minTemp = daily.temperature_2m_min?.[index] ?? fallbackWeather.minTemp;
          const uvIndex = daily.uv_index_max?.[index] ?? fallbackWeather.uvIndex;
          const labelDate = new Date(`${date}T00:00:00+07:00`);
          return {
            date,
            label: labelDate.toLocaleDateString("th-TH", { weekday: "short", day: "numeric", month: "short" }),
            rainChance,
            maxTemp,
            minTemp,
            windSpeed: current.wind_speed_10m ?? fallbackWeather.windSpeed,
            humidity: current.relative_humidity_2m ?? fallbackWeather.humidity,
            uvIndex,
            advice: rainChance >= 60 ? "เตรียมแผนลดน้ำและเลี่ยงงานพ่น" : uvIndex >= 8 || maxTemp >= 35 ? "จัดงานกลางแจ้งช่วงเช้าหรือเย็น" : "ทำงานฟาร์มได้ตามแผน",
          };
        });
        const nextWeather = {
          temperature: current.temperature_2m ?? fallbackWeather.temperature,
          maxTemp: daily.temperature_2m_max?.[0] ?? fallbackWeather.maxTemp,
          minTemp: daily.temperature_2m_min?.[0] ?? fallbackWeather.minTemp,
          humidity: current.relative_humidity_2m ?? fallbackWeather.humidity,
          rainChance: daily.precipitation_probability_max?.[0] ?? fallbackWeather.rainChance,
          rainAmount: daily.precipitation_sum?.[0] ?? current.rain ?? fallbackWeather.rainAmount,
          windSpeed: current.wind_speed_10m ?? fallbackWeather.windSpeed,
          windDirection: windDirectionText(current.wind_direction_10m),
          uvIndex: current.uv_index ?? daily.uv_index_max?.[0] ?? fallbackWeather.uvIndex,
          pressure: current.pressure_msl ?? fallbackWeather.pressure,
          cloudCover: current.cloud_cover ?? fallbackWeather.cloudCover,
          condition: (current.cloud_cover ?? 0) > 70 ? "เมฆมาก" : (current.rain ?? 0) > 0 ? "มีฝน" : "มีเมฆบางส่วน",
          updatedAt: current.time ? new Date(current.time).toLocaleString("th-TH", { dateStyle: "medium", timeStyle: "short" }) : fallbackWeather.updatedAt,
          forecastRows: forecastRows.length ? forecastRows : createFallbackForecastRows(fallbackWeather),
        };
        setWeatherData(nextWeather);
        addWeatherHistoryRecord(nextWeather);
      })
      .catch(() => {
        const nextWeather = { ...fallbackWeather, forecastRows: createFallbackForecastRows(fallbackWeather) };
        setWeatherData(nextWeather);
        addWeatherHistoryRecord(nextWeather);
      })
      .finally(() => active && setWeatherLoading(false));
    return () => { active = false; };
  }, []);
  const submit = (event) => {
    event.preventDefault();
    const numericFields = ["normal", "abnormal", "rowsInspected", "treesPlanted", "laborCount", "hoursWorked", "materialQty", "dailyCost", "progressPercent", "growthRate", "survivalRate"];
    const payload = numericFields.reduce((current, key) => ({ ...current, [key]: Number(form[key]) || 0 }), { ...form });
    onSave({ ...payload, weatherSnapshot: weatherData, id: Date.now(), createdAt: new Date().toLocaleTimeString("th-TH", { hour: "2-digit", minute: "2-digit" }) + " น." });
    setSaved(true);
    window.location.hash = "dashboard";
  };

  return (
    <section id="report-form" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
      <SectionHeader title="ระบบรายงานประจำวัน" subtitle="ฟอร์มสำหรับผู้จัดการฟาร์ม กรอกเหมือน Google Form แล้วส่งขึ้น Dashboard ทันที" />
      <ManagerReportQrPanel />
      <form onSubmit={submit} className="space-y-5">
        <WeatherReportCard weather={weatherData} loading={weatherLoading} form={form} update={update} language={language} />
        <DailyTaskScheduleForm role={role} authProfile={authProfile} onReportReady={setAttachmentReport} />
        <FormSection title="ข้อมูลรายงานประจำวัน" subtitle="กรอกข้อมูลหลักเหมือน Google Form">
          <Input label="วันที่" type="date" value={form.date} onChange={(v) => update("date", v)} />
          <Input label="ชื่อผู้รายงาน" value={form.reporter} onChange={(v) => update("reporter", v)} />
          <Input label="สภาพอากาศ" value={form.weather} onChange={(v) => update("weather", v)} />
          <Select label="แปลง / พื้นที่" value={form.area} onChange={(v) => update("area", v)} options={["แปลง A1", "แปลง A2", "แปลง B1", "คลังวัสดุ", "โรงเรือนเพาะชำ"]} />
          <Textarea label="งานที่ทำวันนี้" value={form.work} onChange={(v) => update("work", v)} />
          <Textarea label="ปัญหาที่พบ" value={form.issue} onChange={(v) => update("issue", v)} />
          <Input label="จำนวนต้นไม้ปกติ" type="number" value={form.normal} onChange={(v) => update("normal", v)} />
          <Input label="จำนวนต้นไม้ผิดปกติ" type="number" value={form.abnormal} onChange={(v) => update("abnormal", v)} />
          <DailyReportAttachmentUploader title="ไฟล์แนบข้อมูลรายงานประจำวัน" sectionName="daily-report-main" report={attachmentReport} role={role} authProfile={authProfile} ensureReport={ensureAttachmentReport} wide />
        </FormSection>
        <FormSection title="ข้อมูลโครงสร้างสำหรับ Analytics / BI" subtitle="ใช้ Dropdown, Number, Plot ID, Row ID และสถานะงาน เพื่อให้ระบบคำนวณ KPI อัตโนมัติ">
          <Select label="Work Type / ประเภทงาน" value={form.workType} onChange={(v) => update("workType", v)} options={["Daily Maintenance", "Tree Inspection", "Planting", "Inventory Withdrawal", "Experiment & R&D", "Water System", "Work Progress", "HR / Personnel", "Cost / Finance"]} />
          <Select label="Status / สถานะงาน" value={form.workStatus} onChange={(v) => update("workStatus", v)} options={["Pending", "In Progress", "Done", "Blocked"]} />
          <Input label="Plot ID / รหัสแปลง" value={form.plotId} onChange={(v) => update("plotId", v)} />
          <Input label="Row ID / รหัสแถว" value={form.rowId} onChange={(v) => update("rowId", v)} />
          <Input label="จำนวนแถวที่ตรวจ" type="number" value={form.rowsInspected} onChange={(v) => update("rowsInspected", v)} />
          <Input label="จำนวนต้นไม้ที่ปลูก" type="number" value={form.treesPlanted} onChange={(v) => update("treesPlanted", v)} />
          <Input label="จำนวนแรงงานที่ใช้" type="number" value={form.laborCount} onChange={(v) => update("laborCount", v)} />
          <Input label="ชั่วโมงทำงานรวม" type="number" value={form.hoursWorked} onChange={(v) => update("hoursWorked", v)} />
          <Select label="วัสดุที่ใช้" value={form.materialUsed} onChange={(v) => update("materialUsed", v)} options={["ไม่ใช้วัสดุ", "ปุ๋ย GS-03", "ปุ๋ยอินทรีย์", "ไบโอชา", "วัสดุคลุมดิน", "น้ำมันดีเซล", "ยา/ชีวภัณฑ์ป้องกันแมลง"]} />
          <Input label="ปริมาณวัสดุที่ใช้" type="number" value={form.materialQty} onChange={(v) => update("materialQty", v)} />
          <Input label="ต้นทุนวันนี้ (บาท)" type="number" value={form.dailyCost} onChange={(v) => update("dailyCost", v)} />
          <Input label="ความคืบหน้างาน (%)" type="number" value={form.progressPercent} onChange={(v) => update("progressPercent", v)} />
          <Input label="Growth Rate (%)" type="number" value={form.growthRate} onChange={(v) => update("growthRate", v)} />
          <Input label="อัตรารอด (%)" type="number" value={form.survivalRate} onChange={(v) => update("survivalRate", v)} />
          <DailyReportAttachmentUploader title="ไฟล์แนบ Analytics / BI" sectionName="analytics-bi" report={attachmentReport} role={role} authProfile={authProfile} ensureReport={ensureAttachmentReport} wide />
        </FormSection>
        <FormSection title="การดูแลและผลการทดลอง" subtitle="บันทึกงานดูแลที่ส่งผลต่อ Dashboard เจ้าของฟาร์ม">
          <Input label="การให้น้ำ" value={form.water} onChange={(v) => update("water", v)} />
          <Input label="การใส่ปุ๋ย" value={form.fertilizer} onChange={(v) => update("fertilizer", v)} />
          <Textarea label="โรคและแมลง" value={form.disease} onChange={(v) => update("disease", v)} />
          <Textarea label="บันทึกการทดลอง" value={form.experiment} onChange={(v) => update("experiment", v)} />
          <DailyReportAttachmentUploader title="ไฟล์แนบการดูแลและผลการทดลอง" sectionName="experiment-care" report={attachmentReport} role={role} authProfile={authProfile} ensureReport={ensureAttachmentReport} wide />
        </FormSection>
        <FormSection title="QR Management ในรายงานประจำวัน" subtitle="สแกนหรือเพิ่มข้อมูล QR ต้นไม้ / แปลง ในฟอร์มเดียวกัน">
          <Select label="สแกน QR ต้นไม้ / แปลง" value={form.qrType} onChange={(v) => update("qrType", v)} options={["QR ต้นไม้", "QR แปลง", "QR อุปกรณ์", "QR รถยนต์", "QR วัสดุฟาร์ม"]} />
          <Input label="Tree ID" value={form.treeId} onChange={(v) => update("treeId", v)} />
          <Input label="Plot / Zone" value={form.plotZone} onChange={(v) => update("plotZone", v)} />
          <Select label="ชนิดต้นไม้" value={form.treeSpecies} onChange={(v) => update("treeSpecies", v)} options={["จามจุรีทอง", "หางนกยูง", "สะเดา", "กัลปพฤกษ์", "ปีบ", "มะฮอกกานี"]} />
          <Select label="สถานะต้นไม้" value={form.treeStatus} onChange={(v) => update("treeStatus", v)} options={["ปกติ", "ต้องติดตาม", "ผิดปกติ", "รอแก้ไข"]} />
          <Textarea label="ปัญหาที่พบจาก QR / Tree ID" value={form.qrIssue} onChange={(v) => update("qrIssue", v)} />
          <Textarea label="หมายเหตุ QR" value={form.qrNote} onChange={(v) => update("qrNote", v)} />
          <DailyReportAttachmentUploader title="ไฟล์แนบ QR Management" sectionName="qr-management" report={attachmentReport} role={role} authProfile={authProfile} ensureReport={ensureAttachmentReport} wide />
        </FormSection>
        <FormSection title="รูปภาพและสรุปส่งเจ้าของฟาร์ม" subtitle="แนบหลักฐานและสรุปภาพรวมเพื่อส่งขึ้น Dashboard ทันที">
          <Textarea label="สรุปงานส่งเจ้าของฟาร์ม" value={form.summary} onChange={(v) => update("summary", v)} wide />
          <DailyReportAttachmentUploader title="ไฟล์แนบสรุปส่งเจ้าของฟาร์ม" sectionName="owner-summary" report={attachmentReport} role={role} authProfile={authProfile} ensureReport={ensureAttachmentReport} wide
            actions={<>
              <button type="button" onClick={generateOwnerSummary} className="inline-flex items-center justify-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="file" className="h-4 w-4" />Generate Owner Summary</button>
              <button type="button" disabled={ownerSummarySaving} onClick={submitAttachmentsToOwner} className="inline-flex items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white hover:bg-goodseed-800 disabled:opacity-60"><Icon name="share" className="h-4 w-4" />Submit to Owner</button>
            </>}
          />
          {ownerSummaryNotice && <div className="md:col-span-2 rounded-lg border border-goodseed-200 bg-white px-4 py-3 text-sm font-bold text-goodseed-800">{ownerSummaryNotice}</div>}
        </FormSection>
        <div className="md:col-span-2 flex flex-col gap-3 sm:flex-row sm:items-center">
          <button className="inline-flex items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-5 py-3 font-extrabold text-white shadow-sm hover:bg-goodseed-800"><Icon name="check" />ส่งรายงาน</button>
          {saved && <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">บันทึกแล้วและแสดงบน Dashboard</Badge>}
        </div>
      </form>
    </section>
  );
}

const dailyTaskScheduleSlots = [
  ["08:00", "09:00", ""],
  ["09:00", "10:00", ""],
  ["10:00", "11:00", ""],
  ["11:00", "12:00", ""],
  ["12:00", "13:00", "พักกลางวัน"],
  ["13:00", "14:00", ""],
  ["14:00", "15:00", ""],
  ["15:00", "16:00", ""],
  ["16:00", "17:00", ""],
];

const dailyReportStatusOptions = ["draft", "submitted", "under_review", "approved", "need_revision", "rejected"];
const dailyReportStatusLabels = {
  draft: "แบบร่าง",
  submitted: "ส่งรายงานแล้ว",
  under_review: "กำลังตรวจสอบ",
  approved: "อนุมัติแล้ว",
  need_revision: "ต้องแก้ไข",
  rejected: "ไม่อนุมัติ",
};

const dailyReportAttachmentBuckets = {
  "daily-report-main": "daily-report-attachments",
  "analytics-bi": "daily-report-attachments",
  "experiment-care": "experiment-attachments",
  "qr-management": "qr-management-attachments",
  "owner-summary": "owner-summary-attachments",
};

const dailyReportFileGroups = [
  { id: "photo", label: "Upload Photo / แนบรูปภาพ", accept: ".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp" },
  { id: "document", label: "Upload Document / แนบเอกสาร", accept: ".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
  { id: "pdf", label: "Upload PDF", accept: ".pdf,application/pdf" },
  { id: "spreadsheet", label: "Upload Excel / CSV", accept: ".xls,.xlsx,.csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv" },
  { id: "other", label: "Upload Other Files", accept: ".jpg,.jpeg,.png,.webp,.pdf,.doc,.docx,.xls,.xlsx,.csv" },
];

const dailyReportAttachmentMaxBytes = 20 * 1024 * 1024;
const allowedDailyReportAttachmentExtensions = ["jpg", "jpeg", "png", "webp", "pdf", "doc", "docx", "xls", "xlsx", "csv"];
const dailyReportAttachmentStatusOptions = ["uploaded", "submitted", "reviewed", "rejected", "need_revision"];
const dailyReportAttachmentStatusLabels = {
  uploaded: "Uploaded / อัปโหลดแล้ว",
  submitted: "Submitted / ส่งแล้ว",
  reviewed: "Reviewed / ตรวจแล้ว",
  rejected: "Rejected / ปฏิเสธ",
  need_revision: "Need Revision / ต้องแก้ไข",
};

function safeStorageName(name = "file") {
  const clean = String(name).normalize("NFKD").replace(/[^\w.\-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
  return clean || `file-${Date.now()}`;
}

function formatFileSize(bytes = 0) {
  const size = Number(bytes) || 0;
  if (size >= 1024 * 1024) return `${(size / 1024 / 1024).toFixed(2)} MB`;
  if (size >= 1024) return `${(size / 1024).toFixed(1)} KB`;
  return `${size} B`;
}

function fileExtension(name = "") {
  return String(name).split(".").pop()?.toLowerCase() || "";
}

function canManageDailyReportAttachments(role) {
  return isOwnerRole(role) || ["admin", "manager", "developer"].includes(role);
}

async function ensureDailyReportForAttachments(client, form, authProfile, role) {
  const { data: userData } = await client.auth.getUser();
  const user = userData?.user;
  const userId = user?.id || authProfile?.id;
  if (!userId) throw new Error("กรุณา Login ด้วยบัญชี Supabase ก่อนแนบไฟล์จริง");
  const employeeName = form.reporter || authProfile?.fullName || authProfile?.full_name || authProfile?.email || user.email || "GoodSeed User";
  const employeeRole = roleInfo(role).label || role || "staff";
  const reportPayload = {
    report_date: form.date || todayInputValue(),
    employee_id: userId,
    employee_name: employeeName,
    employee_role: employeeRole,
    planting_round: "A",
    irrigation_zone: 1,
    completed_summary: form.summary || "",
    unfinished_or_problem_summary: form.issue || "",
    submitted_name: employeeName,
    submitted_signature: employeeName,
    created_by: userId,
    updated_by: userId,
    status: "draft",
  };
  const { data, error } = await client
    .from("daily_reports")
    .upsert(reportPayload, { onConflict: "report_date,employee_id,planting_round,irrigation_zone" })
    .select("*")
    .single();
  if (error) throw error;
  return data;
}

function dailyReportStatusTone(status) {
  return {
    draft: "bg-slate-100 text-slate-700 ring-slate-200",
    submitted: "bg-amber-100 text-amber-800 ring-amber-200",
    under_review: "bg-blue-100 text-blue-700 ring-blue-200",
    approved: "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
    need_revision: "bg-orange-100 text-orange-800 ring-orange-200",
    rejected: "bg-red-100 text-red-700 ring-red-200",
  }[status] || "bg-slate-100 text-slate-700 ring-slate-200";
}

function todayInputValue() {
  return new Date().toLocaleDateString("en-CA", { timeZone: "Asia/Bangkok" });
}

function normalizeScheduleTime(value) {
  return String(value || "").slice(0, 5);
}

function createDailyScheduleRows() {
  return dailyTaskScheduleSlots.map(([timeStart, timeEnd, title], index) => ({
    localId: `slot-${timeStart}-${timeEnd}-${index}`,
    time_start: timeStart,
    time_end: timeEnd,
    task_title: title,
    task_detail: title,
    area_or_planting_round: "",
    responsible_user: "",
    is_completed: false,
    note: "",
  }));
}

function csvEscape(value) {
  return `"${String(value ?? "").replaceAll('"', '""')}"`;
}

function emptyDailySummary(date, authProfile) {
  const name = authProfile?.fullName || authProfile?.full_name || authProfile?.email || "";
  return {
    id: "",
    report_code: "",
    report_date: date,
    planting_round: "A",
    irrigation_zone: "1",
    employee_name: name,
    employee_role: "staff",
    completed_summary: "",
    unfinished_or_problem_summary: "",
    checklist_daily_inspection: false,
    checklist_equipment_ready: false,
    checklist_inventory_log: false,
    checklist_planting_experiment: false,
    submitted_name: name,
    submitted_signature: name,
    status: "draft",
    submitted_at: null,
    submit_datetime: null,
    review_note: "",
  };
}

function LegacyDailyTaskScheduleForm({ role = "owner", authProfile }) {
  const [reportDate, setReportDate] = useState(todayInputValue());
  const [rows, setRows] = useState(createDailyScheduleRows);
  const [summary, setSummary] = useState(() => emptyDailySummary(todayInputValue(), authProfile));
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState("");
  const canManageAllReports = isOwnerRole(role) || ["admin", "manager", "developer"].includes(role);
  const canUseSchedule = canManageAllReports || ["staff", "worker"].includes(role);
  const storageKey = `goodseed-daily-task-schedule:${reportDate}:${authProfile?.id || authProfile?.email || role}`;

  const updateRow = (localId, key, value) => {
    setRows((current) => current.map((row) => (row.localId === localId ? { ...row, [key]: value } : row)));
  };
  const updateSummary = (key, value) => setSummary((current) => ({ ...current, [key]: value }));

  const addRow = () => {
    setRows((current) => [...current, {
      localId: `custom-${Date.now()}`,
      time_start: "08:00",
      time_end: "09:00",
      task_title: "",
      task_detail: "",
      area_or_planting_round: "",
      responsible_user: authProfile?.fullName || authProfile?.full_name || "",
      is_completed: false,
      note: "",
    }]);
  };

  const deleteRow = (localId) => {
    setRows((current) => current.length > 1 ? current.filter((row) => row.localId !== localId) : current);
  };

  const loadLocalSchedule = () => {
    try {
      const saved = JSON.parse(window.localStorage?.getItem(storageKey) || "null");
      if (saved?.rows?.length) setRows(saved.rows);
      if (saved?.summary) setSummary({ ...emptyDailySummary(reportDate, authProfile), ...saved.summary });
    } catch (error) {
      console.warn("GoodSeed daily schedule local load failed", error);
    }
  };

  useEffect(() => {
    let active = true;
    const loadSchedule = async () => {
      setLoading(true);
      setNotice("");
      const client = getSupabaseClient({ silent: true });
      if (!client) {
        loadLocalSchedule();
        setNotice("ยังไม่พบ Supabase env จึงแสดงข้อมูลที่บันทึกในเครื่องนี้ชั่วคราว");
        setLoading(false);
        return;
      }
      try {
        const { data: userData } = await client.auth.getUser();
        const userId = userData?.user?.id;
        let taskQuery = client.from("daily_hourly_tasks").select("*").eq("report_date", reportDate).order("time_start", { ascending: true });
        let summaryQuery = client.from("daily_report_summary").select("*").eq("report_date", reportDate).order("updated_at", { ascending: false }).limit(1);
        if (!canManageAllReports && userId) {
          taskQuery = taskQuery.eq("created_by", userId);
          summaryQuery = summaryQuery.eq("submitted_by", userId);
        }
        const [{ data: taskData, error: taskError }, { data: summaryData, error: summaryError }] = await Promise.all([taskQuery, summaryQuery]);
        if (taskError || summaryError) throw taskError || summaryError;
        if (!active) return;
        setRows(taskData?.length ? taskData.map((task) => ({
          localId: task.id,
          id: task.id,
          time_start: normalizeScheduleTime(task.time_start),
          time_end: normalizeScheduleTime(task.time_end),
          task_title: task.task_title || "",
          task_detail: task.task_detail || "",
          area_or_planting_round: task.area_or_planting_round || "",
          responsible_user: task.responsible_user || "",
          is_completed: Boolean(task.is_completed),
          note: task.note || "",
          created_by: task.created_by || "",
        })) : createDailyScheduleRows());
        setSummary({ ...emptyDailySummary(reportDate, authProfile), ...(summaryData?.[0] || {}) });
      } catch (error) {
        console.warn("GoodSeed daily schedule Supabase load failed", error);
        if (!active) return;
        loadLocalSchedule();
        setNotice("ยังอ่านตารางจาก Supabase ไม่ได้ กรุณารัน supabase/daily_report_schedule.sql ใน SQL Editor ก่อน");
      } finally {
        if (active) setLoading(false);
      }
    };
    loadSchedule();
    return () => { active = false; };
  }, [reportDate, canManageAllReports, authProfile?.id, authProfile?.email]);

  const saveSchedule = async (nextStatus = summary.status) => {
    if (!canUseSchedule) return;
    setSaving(true);
    setNotice("");
    const submittedAt = nextStatus === "submitted" ? new Date().toISOString() : summary.submitted_at;
    const nextSummary = { ...summary, status: nextStatus, report_date: reportDate, submitted_at: submittedAt };
    try {
      const client = getSupabaseClient({ silent: true });
      const { data: userData } = client ? await client.auth.getUser() : { data: null };
      const userId = userData?.user?.id || authProfile?.id || null;
      if (!client || !userId) throw new Error("missing-supabase-session");
      let deleteQuery = client.from("daily_hourly_tasks").delete().eq("report_date", reportDate);
      if (!canManageAllReports) deleteQuery = deleteQuery.eq("created_by", userId);
      const { error: deleteError } = await deleteQuery;
      if (deleteError) throw deleteError;
      const taskPayload = rows.map((row) => ({
        report_date: reportDate,
        time_start: row.time_start,
        time_end: row.time_end,
        task_title: row.task_title || "",
        task_detail: row.task_detail || "",
        area_or_planting_round: row.area_or_planting_round || "",
        responsible_user: row.responsible_user || "",
        is_completed: Boolean(row.is_completed),
        note: row.note || "",
        created_by: canManageAllReports ? (row.created_by || userId) : userId,
      }));
      if (taskPayload.length) {
        const { error: taskError } = await client.from("daily_hourly_tasks").insert(taskPayload);
        if (taskError) throw taskError;
      }
      const { error: summaryError } = await client.from("daily_report_summary").upsert({
        ...nextSummary,
        submitted_by: userId,
        submitted_name: nextSummary.submitted_name || authProfile?.fullName || authProfile?.full_name || authProfile?.email || "",
        submitted_signature: nextSummary.submitted_signature || nextSummary.submitted_name || "",
      }, { onConflict: "report_date,submitted_by" });
      if (summaryError) throw summaryError;
      setSummary(nextSummary);
      setRows((current) => current.map((row, index) => ({ ...row, localId: row.id || `${row.time_start}-${row.time_end}-${index}` })));
      setNotice(nextStatus === "submitted" ? "ส่งรายงานแล้ว ระบบบันทึกเวลาส่งเรียบร้อย" : "บันทึก Draft แล้ว");
    } catch (error) {
      console.warn("GoodSeed daily schedule save failed", error);
      try {
        window.localStorage?.setItem(storageKey, JSON.stringify({ rows, summary: nextSummary }));
        setSummary(nextSummary);
        setNotice("บันทึกในเครื่องนี้ชั่วคราวแล้ว แต่ยังส่งเข้า Supabase ไม่ได้ กรุณารันไฟล์ SQL ตารางงานรายชั่วโมง");
      } catch (storageError) {
        setNotice("บันทึกไม่สำเร็จ กรุณาตรวจ Supabase SQL และลองใหม่อีกครั้ง");
      }
    } finally {
      setSaving(false);
    }
  };

  if (!canUseSchedule) return null;

  return (
    <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <p className="text-sm font-extrabold text-goodseed-700">08.00 - 17.00 น.</p>
          <h3 className="mt-1 text-2xl font-black text-goodseed-950">ตารางงานรายชั่วโมง / Daily Task Schedule</h3>
          <p className="mt-1 text-sm font-semibold text-goodseed-700">ใช้แทนกระดาษตารางงานรายวัน บันทึกเป็น Draft, Submitted หรือ Reviewed เพื่อวิเคราะห์ KPI ย้อนหลัง</p>
        </div>
        <div className="grid gap-2 sm:grid-cols-2 lg:min-w-[360px]">
          <Input label="วันที่รายงาน" type="date" value={reportDate} onChange={setReportDate} />
          <Select label="สถานะ" value={summary.status || "draft"} onChange={(value) => updateSummary("status", value)} options={["draft", "submitted", "reviewed"]} />
        </div>
      </div>
      {notice && <div className="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-bold text-amber-800">{notice}</div>}
      {loading ? <div className="mt-4 rounded-lg bg-goodseed-50 p-4 text-sm font-bold text-goodseed-700">กำลังโหลดตารางงาน...</div> : (
        <div className="mt-5 space-y-3">
          {rows.map((row) => (
            <div key={row.localId} className="grid gap-3 rounded-lg border border-goodseed-100 bg-goodseed-50/70 p-3 xl:grid-cols-[120px_1fr_1fr_150px_150px_96px_1fr_44px] xl:items-end">
              <div className="grid grid-cols-2 gap-2 lg:block">
                <Input label="เริ่ม" type="time" value={row.time_start} onChange={(value) => updateRow(row.localId, "time_start", value)} />
                <Input label="สิ้นสุด" type="time" value={row.time_end} onChange={(value) => updateRow(row.localId, "time_end", value)} />
              </div>
              <Input label="งานที่ต้องทำ" value={row.task_title} onChange={(value) => updateRow(row.localId, "task_title", value)} />
              <Input label="รายละเอียดงาน" value={row.task_detail} onChange={(value) => updateRow(row.localId, "task_detail", value)} />
              <Input label="พื้นที่ / รอบปลูก" value={row.area_or_planting_round} onChange={(value) => updateRow(row.localId, "area_or_planting_round", value)} />
              <Input label="ผู้รับผิดชอบ" value={row.responsible_user} onChange={(value) => updateRow(row.localId, "responsible_user", value)} />
              <label className="flex min-h-[42px] items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-sm font-black text-goodseed-800">
                <input type="checkbox" checked={row.is_completed} onChange={(event) => updateRow(row.localId, "is_completed", event.target.checked)} className="h-4 w-4 accent-goodseed-700" />
                เสร็จแล้ว
              </label>
              <Input label="หมายเหตุ" value={row.note} onChange={(value) => updateRow(row.localId, "note", value)} />
              <button type="button" onClick={() => deleteRow(row.localId)} className="grid h-11 place-items-center rounded-lg border border-red-200 bg-white text-red-700 hover:bg-red-50" title="ลบรายการ"><Icon name="trash" className="h-4 w-4" /></button>
            </div>
          ))}
          <button type="button" onClick={addRow} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="plus" className="h-4 w-4" />เพิ่มรายการงาน</button>
        </div>
      )}
      <div className="mt-5 grid gap-4 lg:grid-cols-2">
        <Textarea label="งานที่เสร็จตามแผน" value={summary.completed_summary || ""} onChange={(value) => updateSummary("completed_summary", value)} />
        <Textarea label="งานที่ยังไม่เสร็จ / พบปัญหา" value={summary.unfinished_or_problem_summary || ""} onChange={(value) => updateSummary("unfinished_or_problem_summary", value)} />
      </div>
      <div className="mt-5 rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
        <h4 className="font-black text-goodseed-950">Checklist ส่งรายงานประจำวัน</h4>
        <div className="mt-3 grid gap-3 md:grid-cols-2">
          {[
            ["checklist_daily_inspection", "ส่งแบบฟอร์มการตรวจแปลงประจำวัน"],
            ["checklist_equipment_ready", "ตรวจเช็คความพร้อมอุปกรณ์"],
            ["checklist_inventory_log", "บันทึกการนำเข้าและเบิกใช้ของ"],
            ["checklist_planting_experiment", "บันทึกการปลูกและทดลอง"],
          ].map(([key, label]) => (
            <label key={key} className="flex items-center gap-2 rounded-lg bg-white px-3 py-2 text-sm font-bold text-goodseed-800 ring-1 ring-goodseed-100">
              <input type="checkbox" checked={Boolean(summary[key])} onChange={(event) => updateSummary(key, event.target.checked)} className="h-4 w-4 accent-goodseed-700" />
              {label}
            </label>
          ))}
        </div>
      </div>
      <div className="mt-5 grid gap-4 md:grid-cols-3">
        <Input label="ชื่อผู้ปฏิบัติงาน" value={summary.submitted_name || ""} onChange={(value) => updateSummary("submitted_name", value)} />
        <Input label="วันที่" type="date" value={reportDate} onChange={setReportDate} />
        <Input label="ลายเซ็น / ชื่อผู้ส่งรายงาน" value={summary.submitted_signature || ""} onChange={(value) => updateSummary("submitted_signature", value)} />
      </div>
      <div className="mt-5 flex flex-col gap-3 sm:flex-row sm:items-center">
        <button type="button" disabled={saving} onClick={() => saveSchedule("draft")} className="inline-flex items-center justify-center gap-2 rounded-lg border border-goodseed-200 bg-white px-5 py-3 font-extrabold text-goodseed-800 hover:bg-goodseed-50 disabled:opacity-60"><Icon name="save" className="h-4 w-4" />บันทึก Draft</button>
        <button type="button" disabled={saving} onClick={() => saveSchedule("submitted")} className="inline-flex items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-5 py-3 font-extrabold text-white shadow-sm hover:bg-goodseed-800 disabled:opacity-60"><Icon name="check" className="h-4 w-4" />Submit ส่งรายงาน</button>
        {summary.submitted_at && <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">ส่งเมื่อ {new Date(summary.submitted_at).toLocaleString("th-TH", { dateStyle: "medium", timeStyle: "short" })}</Badge>}
      </div>
    </div>
  );
}

function DailyTaskScheduleForm({ role = "owner", authProfile, onReportReady }) {
  const [reportDate, setReportDate] = useState(todayInputValue());
  const [rows, setRows] = useState(createDailyScheduleRows);
  const [summary, setSummary] = useState(() => emptyDailySummary(todayInputValue(), authProfile));
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState("");
  const canManageAllReports = isOwnerRole(role) || ["admin", "manager", "developer"].includes(role);
  const canUseSchedule = canManageAllReports || ["staff", "worker"].includes(role);
  const employeeName = authProfile?.fullName || authProfile?.full_name || authProfile?.email || "";
  const employeeRole = roleInfo(role).label || role;
  const reportLocked = !canManageAllReports && !["draft", "need_revision"].includes(summary.status || "draft");

  const updateRow = (localId, key, value) => setRows((current) => current.map((row) => (row.localId === localId ? { ...row, [key]: value } : row)));
  const updateSummary = (key, value) => setSummary((current) => ({ ...current, [key]: value }));
  const addRow = () => setRows((current) => [...current, { ...createDailyScheduleRows()[0], localId: `custom-${Date.now()}`, task_title: "", task_detail: "", responsible_user: employeeName }]);
  const deleteRow = (localId) => setRows((current) => current.length > 1 ? current.filter((row) => row.localId !== localId) : current);

  useEffect(() => {
    let active = true;
    const loadSchedule = async () => {
      setLoading(true);
      setNotice("");
      const client = getSupabaseClient({ silent: true });
      if (!client) {
        setRows(createDailyScheduleRows());
        setSummary(emptyDailySummary(reportDate, authProfile));
        setNotice("ยังไม่พบ Supabase env จึงยังบันทึก Draft/Submit ไม่ได้");
        setLoading(false);
        return;
      }
      try {
        const { data: userData } = await client.auth.getUser();
        const userId = userData?.user?.id;
        let reportQuery = client
          .from("daily_reports")
          .select("*")
          .eq("report_date", reportDate)
          .eq("planting_round", summary.planting_round || "A")
          .eq("irrigation_zone", Number(summary.irrigation_zone || 1))
          .order("updated_at", { ascending: false })
          .limit(1);
        if (!canManageAllReports && userId) reportQuery = reportQuery.eq("employee_id", userId);
        const { data: reportRows, error: reportError } = await reportQuery;
        if (reportError) throw reportError;
        if (!active) return;
        const report = reportRows?.[0];
        if (!report) {
          setRows(createDailyScheduleRows());
          setSummary(emptyDailySummary(reportDate, authProfile));
          return;
        }
        onReportReady?.(report);
        const { data: taskData, error: taskError } = await client
          .from("daily_report_tasks")
          .select("*")
          .eq("report_id", report.id)
          .order("sort_order", { ascending: true })
          .order("time_start", { ascending: true });
        if (taskError) throw taskError;
        if (!active) return;
        setRows(taskData?.length ? taskData.map((task) => ({
          localId: task.id,
          id: task.id,
          time_start: normalizeScheduleTime(task.time_start),
          time_end: normalizeScheduleTime(task.time_end),
          task_title: task.task_title || "",
          task_detail: task.task_detail || "",
          area_or_planting_round: task.area_or_planting_round || "",
          responsible_user: task.responsible_user || "",
          is_completed: Boolean(task.is_completed),
          note: task.note || "",
          created_by: task.created_by || "",
          updated_by: task.updated_by || "",
        })) : createDailyScheduleRows());
        setSummary({
          ...emptyDailySummary(reportDate, authProfile),
          id: report.id,
          report_code: report.report_code || "",
          employee_id: report.employee_id || "",
          employee_name: report.employee_name || employeeName,
          employee_role: report.employee_role || employeeRole,
          planting_round: report.planting_round || "A",
          irrigation_zone: String(report.irrigation_zone || 1),
          completed_summary: report.completed_summary || "",
          unfinished_or_problem_summary: report.unfinished_or_problem_summary || "",
          checklist_daily_inspection: Boolean(report.checklist_daily_inspection),
          checklist_equipment_ready: Boolean(report.checklist_equipment_ready),
          checklist_inventory_log: Boolean(report.checklist_inventory_log),
          checklist_planting_experiment: Boolean(report.checklist_planting_experiment),
          submitted_name: report.submitted_name || report.employee_name || employeeName,
          submitted_signature: report.submitted_signature || "",
          status: report.status || "draft",
          submit_datetime: report.submit_datetime || null,
          submitted_at: report.submit_datetime || null,
          review_note: report.review_note || "",
          created_by: report.created_by || "",
          updated_by: report.updated_by || "",
        });
      } catch (error) {
        console.warn("GoodSeed production daily report load failed", error);
        if (!active) return;
        setRows(createDailyScheduleRows());
        setSummary(emptyDailySummary(reportDate, authProfile));
        setNotice("ยังอ่านตาราง Daily Report จาก Supabase ไม่ได้ กรุณารัน supabase/daily_report_schedule.sql เวอร์ชันล่าสุดใน SQL Editor ก่อน");
      } finally {
        if (active) setLoading(false);
      }
    };
    loadSchedule();
    return () => { active = false; };
  }, [reportDate, summary.planting_round, summary.irrigation_zone, canManageAllReports, authProfile?.id, authProfile?.email]);

  const saveSchedule = async (nextStatus = "draft") => {
    if (!canUseSchedule) return;
    if (reportLocked) {
      setNotice("รายงานนี้ Submit แล้ว แก้ไขไม่ได้จนกว่า Owner หรือ Manager จะเปลี่ยนสถานะเป็น Need Revision");
      return;
    }
    setSaving(true);
    setNotice("");
    try {
      const client = getSupabaseClient({ silent: true });
      const { data: userData } = client ? await client.auth.getUser() : { data: null };
      const userId = userData?.user?.id || authProfile?.id || null;
      if (!client || !userId) throw new Error("missing-supabase-session");
      const reportPayload = {
        report_date: reportDate,
        employee_id: summary.employee_id || userId,
        employee_name: summary.employee_name || employeeName,
        employee_role: summary.employee_role || employeeRole,
        planting_round: summary.planting_round || "A",
        irrigation_zone: Number(summary.irrigation_zone || 1),
        completed_summary: summary.completed_summary || "",
        unfinished_or_problem_summary: summary.unfinished_or_problem_summary || "",
        checklist_daily_inspection: Boolean(summary.checklist_daily_inspection),
        checklist_equipment_ready: Boolean(summary.checklist_equipment_ready),
        checklist_inventory_log: Boolean(summary.checklist_inventory_log),
        checklist_planting_experiment: Boolean(summary.checklist_planting_experiment),
        submitted_name: summary.submitted_name || summary.employee_name || employeeName,
        submitted_signature: summary.submitted_signature || "",
        created_by: summary.created_by || userId,
        updated_by: userId,
        status: nextStatus === "submitted" ? "draft" : nextStatus,
      };
      const { data: reportData, error: reportError } = await client
        .from("daily_reports")
        .upsert(reportPayload, { onConflict: "report_date,employee_id,planting_round,irrigation_zone" })
        .select("*")
        .single();
      if (reportError) throw reportError;
      const { error: deleteError } = await client.from("daily_report_tasks").delete().eq("report_id", reportData.id);
      if (deleteError) throw deleteError;
      const taskPayload = rows.map((row, index) => ({
        report_id: reportData.id,
        time_start: row.time_start,
        time_end: row.time_end,
        task_title: row.task_title || "",
        task_detail: row.task_detail || "",
        area_or_planting_round: row.area_or_planting_round || "",
        responsible_user: row.responsible_user || "",
        is_completed: Boolean(row.is_completed),
        note: row.note || "",
        sort_order: index + 1,
        created_by: row.created_by || userId,
        updated_by: userId,
      }));
      if (taskPayload.length) {
        const { error: taskError } = await client.from("daily_report_tasks").insert(taskPayload);
        if (taskError) throw taskError;
      }
      let finalReport = reportData;
      if (nextStatus === "submitted") {
        const { data: submittedReport, error: submitError } = await client
          .from("daily_reports")
          .update({
            status: "submitted",
            submit_datetime: new Date().toISOString(),
            submitted_by: userId,
            submitted_name: reportPayload.submitted_name,
            submitted_role: employeeRole,
            updated_by: userId,
          })
          .eq("id", reportData.id)
          .select("*")
          .single();
        if (submitError) throw submitError;
        finalReport = submittedReport;
      }
      setSummary((current) => ({
        ...current,
        ...reportPayload,
        id: finalReport.id,
        report_code: finalReport.report_code || "",
        status: finalReport.status,
        submit_datetime: finalReport.submit_datetime || null,
        submitted_at: finalReport.submit_datetime || null,
      }));
      onReportReady?.(finalReport);
      setNotice(nextStatus === "submitted" ? "ส่งรายงานแล้ว ระบบบันทึกเวลาส่งและแจ้งเตือน Owner เรียบร้อย" : "บันทึก Draft ลง Supabase แล้ว");
    } catch (error) {
      console.warn("GoodSeed production daily report save failed", error);
      setNotice(`บันทึกลง Supabase ไม่สำเร็จ: ${supabaseAuthMessage(error)} กรุณารัน supabase/daily_report_schedule.sql เวอร์ชันล่าสุดและลองใหม่`);
    } finally {
      setSaving(false);
    }
  };

  const reportRowsForExport = rows.map((row) => [`${row.time_start}-${row.time_end}`, row.task_title, row.task_detail, row.area_or_planting_round, row.responsible_user, row.is_completed ? "Done" : "Pending", row.note]);
  const downloadExcel = () => {
    const header = ["เวลา", "งานที่ต้องทำ", "รายละเอียดงาน", "พื้นที่ / จุดงาน", "ผู้รับผิดชอบ", "สถานะ", "หมายเหตุ"];
    downloadFile(`daily-report-${reportDate}.csv`, `\ufeff${[header, ...reportRowsForExport].map((row) => row.map(csvEscape).join(",")).join("\n")}`, "text/csv;charset=utf-8");
  };
  const downloadPdf = () => {
    const html = `<html><meta charset="utf-8"><body><h1>GOODSEED Farm Daily Report</h1><p>Report ID: ${summary.report_code || summary.id || "-"}</p><p>Date: ${reportDate}</p><p>Employee: ${summary.employee_name}</p><p>Status: ${summary.status}</p><table border="1" cellspacing="0" cellpadding="6"><tr><th>Time</th><th>Task</th><th>Detail</th><th>Area</th><th>Owner</th><th>Status</th><th>Note</th></tr>${reportRowsForExport.map((row) => `<tr>${row.map((cell) => `<td>${String(cell || "")}</td>`).join("")}</tr>`).join("")}</table><h2>Summary</h2><p>${summary.completed_summary || ""}</p><p>${summary.unfinished_or_problem_summary || ""}</p></body></html>`;
    downloadFile(`daily-report-${reportDate}.html`, html, "text/html;charset=utf-8");
  };

  if (!canUseSchedule) return null;

  return (
    <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <p className="text-sm font-extrabold text-goodseed-700">08.00 - 17.00 น.</p>
          <h3 className="mt-1 text-2xl font-black text-goodseed-950">ตารางงานรายชั่วโมง / Daily Task Schedule</h3>
          <p className="mt-2 flex flex-wrap items-center gap-2 text-sm font-semibold text-goodseed-700">Report ID: {summary.report_code || summary.id || "ยังไม่บันทึก"} <Badge className={dailyReportStatusTone(summary.status)}>{dailyReportStatusLabels[summary.status] || summary.status}</Badge></p>
        </div>
        <div className="grid gap-2 sm:grid-cols-2 lg:min-w-[360px]">
          <Input label="วันที่รายงาน" type="date" value={reportDate} onChange={setReportDate} />
          <Select label="สถานะ" value={summary.status || "draft"} onChange={(value) => updateSummary("status", value)} options={dailyReportStatusOptions} />
        </div>
      </div>
      <div className="mt-4 grid gap-3 md:grid-cols-4">
        <MiniMetric label="Employee ID" value={(authProfile?.id || summary.employee_id || "-").slice(0, 8)} />
        <MiniMetric label="Employee Name" value={summary.employee_name || employeeName || "-"} />
        <MiniMetric label="Position / Role" value={summary.employee_role || employeeRole} />
        <MiniMetric label="Submit DateTime" value={summary.submit_datetime ? new Date(summary.submit_datetime).toLocaleString("th-TH", { dateStyle: "medium", timeStyle: "short" }) : "-"} />
      </div>
      {reportLocked && <div className="mt-4 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-sm font-bold text-blue-800">รายงานนี้ Submit แล้ว แก้ไขไม่ได้จนกว่า Owner หรือ Manager จะเปลี่ยนสถานะเป็น Need Revision</div>}
      {notice && <div className="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-bold text-amber-800">{notice}</div>}
      {loading ? <div className="mt-4 rounded-lg bg-goodseed-50 p-4 text-sm font-bold text-goodseed-700">กำลังโหลดตารางงาน...</div> : (
        <div className="mt-5 space-y-3">
          {rows.map((row) => (
            <div key={row.localId} className="grid gap-3 rounded-lg border border-goodseed-100 bg-goodseed-50/70 p-3 xl:grid-cols-[120px_1fr_1fr_150px_150px_96px_1fr_44px] xl:items-end">
              <div className="grid grid-cols-2 gap-2 lg:block">
                <Input label="เริ่ม" type="time" value={row.time_start} onChange={(value) => updateRow(row.localId, "time_start", value)} />
                <Input label="สิ้นสุด" type="time" value={row.time_end} onChange={(value) => updateRow(row.localId, "time_end", value)} />
              </div>
              <Input label="งานที่ต้องทำ" value={row.task_title} onChange={(value) => updateRow(row.localId, "task_title", value)} />
              <Input label="รายละเอียดงาน" value={row.task_detail} onChange={(value) => updateRow(row.localId, "task_detail", value)} />
              <Input label="พื้นที่ / จุดงาน" value={row.area_or_planting_round} onChange={(value) => updateRow(row.localId, "area_or_planting_round", value)} />
              <Input label="ผู้รับผิดชอบ" value={row.responsible_user} onChange={(value) => updateRow(row.localId, "responsible_user", value)} />
              <label className="flex min-h-[42px] items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-sm font-black text-goodseed-800">
                <input type="checkbox" disabled={reportLocked} checked={row.is_completed} onChange={(event) => updateRow(row.localId, "is_completed", event.target.checked)} className="h-4 w-4 accent-goodseed-700" />
                เสร็จแล้ว
              </label>
              <Input label="หมายเหตุ" value={row.note} onChange={(value) => updateRow(row.localId, "note", value)} />
              <button type="button" disabled={reportLocked} onClick={() => deleteRow(row.localId)} className="grid h-11 place-items-center rounded-lg border border-red-200 bg-white text-red-700 hover:bg-red-50 disabled:opacity-40" title="ลบรายการ"><Icon name="trash" className="h-4 w-4" /></button>
            </div>
          ))}
          <button type="button" disabled={reportLocked} onClick={addRow} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50 disabled:opacity-40"><Icon name="plus" className="h-4 w-4" />เพิ่มรายการงาน</button>
        </div>
      )}
      <div className="mt-5 grid gap-4 lg:grid-cols-2">
        <Textarea label="งานที่เสร็จตามแผน" value={summary.completed_summary || ""} onChange={(value) => updateSummary("completed_summary", value)} />
        <Textarea label="งานที่ยังไม่เสร็จ / พบปัญหา" value={summary.unfinished_or_problem_summary || ""} onChange={(value) => updateSummary("unfinished_or_problem_summary", value)} />
      </div>
      <div className="mt-5 rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
        <h4 className="font-black text-goodseed-950">Checklist ส่งรายงานประจำวัน</h4>
        <div className="mt-3 grid gap-3 md:grid-cols-2">
          {[["checklist_daily_inspection", "ส่งแบบฟอร์มการตรวจแปลงประจำวัน"], ["checklist_equipment_ready", "ตรวจเช็คความพร้อมอุปกรณ์"], ["checklist_inventory_log", "บันทึกการนำเข้าและเบิกใช้ของ"], ["checklist_planting_experiment", "บันทึกการปลูกและทดลอง"]].map(([key, label]) => (
            <label key={key} className="flex items-center gap-2 rounded-lg bg-white px-3 py-2 text-sm font-bold text-goodseed-800 ring-1 ring-goodseed-100">
              <input type="checkbox" disabled={reportLocked} checked={Boolean(summary[key])} onChange={(event) => updateSummary(key, event.target.checked)} className="h-4 w-4 accent-goodseed-700" />
              {label}
            </label>
          ))}
        </div>
      </div>
      <div className="mt-5 grid gap-4 md:grid-cols-3">
        <Input label="ชื่อผู้ปฏิบัติงาน" value={summary.employee_name || ""} onChange={(value) => updateSummary("employee_name", value)} />
        <Input label="วันที่" type="date" value={reportDate} onChange={setReportDate} />
        <Input label="ลายเซ็น / ชื่อผู้ส่งรายงาน" value={summary.submitted_signature || ""} onChange={(value) => updateSummary("submitted_signature", value)} />
      </div>
      <div className="mt-5 flex flex-col gap-3 sm:flex-row sm:items-center">
        <button type="button" disabled={saving || reportLocked} onClick={() => saveSchedule("draft")} className="inline-flex items-center justify-center gap-2 rounded-lg border border-goodseed-200 bg-white px-5 py-3 font-extrabold text-goodseed-800 hover:bg-goodseed-50 disabled:opacity-60"><Icon name="save" className="h-4 w-4" />Save Draft</button>
        <button type="button" disabled={saving || reportLocked} onClick={() => saveSchedule("submitted")} className="inline-flex items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-5 py-3 font-extrabold text-white shadow-sm hover:bg-goodseed-800 disabled:opacity-60"><Icon name="check" className="h-4 w-4" />Submit Report</button>
        <button type="button" onClick={downloadPdf} className="inline-flex items-center justify-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="download" className="h-4 w-4" />Download PDF</button>
        <button type="button" onClick={downloadExcel} className="inline-flex items-center justify-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="download" className="h-4 w-4" />Download Excel</button>
        <button type="button" onClick={() => window.print()} className="inline-flex items-center justify-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="file" className="h-4 w-4" />Print Report</button>
      </div>
    </div>
  );
}

function DailyReportAttachmentUploader({ title, sectionName, report, role = "staff", authProfile, ensureReport, wide = false, actions = null }) {
  const inputRef = useRef(null);
  const [accept, setAccept] = useState(dailyReportFileGroups[4].accept);
  const [uploadGroup, setUploadGroup] = useState("other");
  const [description, setDescription] = useState("");
  const [attachments, setAttachments] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [notice, setNotice] = useState("");
  const [currentUserId, setCurrentUserId] = useState(authProfile?.id || "");
  const bucket = dailyReportAttachmentBuckets[sectionName] || "daily-report-attachments";
  const canManageFiles = canManageDailyReportAttachments(role);

  const loadAttachments = async (reportId = report?.id) => {
    if (!reportId) return;
    const client = getSupabaseClient({ silent: true });
    if (!client) return;
    try {
      const { data: userData } = await client.auth.getUser();
      setCurrentUserId(userData?.user?.id || authProfile?.id || "");
      const { data, error } = await client
        .from("daily_report_attachments")
        .select("*")
        .eq("report_id", reportId)
        .eq("section_name", sectionName)
        .order("uploaded_at", { ascending: false });
      if (error) throw error;
      const enriched = await Promise.all((data || []).map(async (item) => {
        const itemBucket = item.metadata?.bucket || bucket;
        const path = item.storage_path || item.metadata?.storage_path;
        if (!path) return item;
        const { data: signed } = await client.storage.from(itemBucket).createSignedUrl(path, 60 * 60);
        return { ...item, signed_url: signed?.signedUrl || item.file_url };
      }));
      setAttachments(enriched);
    } catch (error) {
      console.warn("GoodSeed attachment load failed", error);
      setNotice(`อ่านไฟล์แนบไม่ได้: ${supabaseAuthMessage(error)}`);
    }
  };

  useEffect(() => {
    loadAttachments(report?.id);
  }, [report?.id, sectionName]);

  const openPicker = (group) => {
    const nextGroup = dailyReportFileGroups.find((item) => item.id === group) || dailyReportFileGroups[4];
    setAccept(nextGroup.accept);
    setUploadGroup(nextGroup.id);
    window.setTimeout(() => inputRef.current?.click(), 0);
  };

  const uploadFiles = async (event) => {
    const files = Array.from(event.target.files || []);
    event.target.value = "";
    if (!files.length) return;
    setUploading(true);
    setNotice("");
    try {
      const invalid = files.find((file) => !allowedDailyReportAttachmentExtensions.includes(fileExtension(file.name)) || file.size > dailyReportAttachmentMaxBytes);
      if (invalid) throw new Error(`${invalid.name} ไม่รองรับหรือไฟล์ใหญ่เกิน 20 MB`);
      const { client, report: activeReport } = await ensureReport();
      const { data: userData } = await client.auth.getUser();
      const userId = userData?.user?.id || authProfile?.id;
      if (!userId) throw new Error("กรุณา Login ก่อนอัปโหลดไฟล์");
      for (const file of files) {
        const storagePath = `${activeReport.id}/${sectionName}/${Date.now()}-${safeStorageName(file.name)}`;
        const { error: uploadError } = await client.storage.from(bucket).upload(storagePath, file, {
          cacheControl: "3600",
          contentType: file.type || "application/octet-stream",
          upsert: false,
        });
        if (uploadError) throw uploadError;
        const { data: signed } = await client.storage.from(bucket).createSignedUrl(storagePath, 60 * 60);
        const { error: insertError } = await client.from("daily_report_attachments").insert({
          report_id: activeReport.id,
          section_name: sectionName,
          file_name: file.name,
          file_type: file.type || fileExtension(file.name),
          file_size: file.size,
          file_url: signed?.signedUrl || "",
          storage_path: storagePath,
          uploaded_by: userId,
          uploaded_at: new Date().toISOString(),
          description,
          status: "uploaded",
          metadata: { bucket, upload_group: uploadGroup, original_name: file.name },
        });
        if (insertError) throw insertError;
      }
      setDescription("");
      await loadAttachments(activeReport.id);
      setNotice(`อัปโหลดสำเร็จ ${files.length} ไฟล์ และบันทึก metadata ลง Supabase แล้ว`);
    } catch (error) {
      console.warn("GoodSeed attachment upload failed", error);
      setNotice(`อัปโหลดไม่สำเร็จ: ${supabaseAuthMessage(error)}`);
    } finally {
      setUploading(false);
    }
  };

  const deleteAttachment = async (attachment) => {
    const client = getSupabaseClient({ silent: true });
    if (!client) return;
    const { data: userData } = await client.auth.getUser();
    const userId = userData?.user?.id || authProfile?.id;
    if (!canManageFiles && attachment.uploaded_by !== userId) {
      setNotice("ลบไฟล์ได้เฉพาะเจ้าของไฟล์ / Manager / Owner");
      return;
    }
    try {
      const itemBucket = attachment.metadata?.bucket || bucket;
      if (attachment.storage_path) await client.storage.from(itemBucket).remove([attachment.storage_path]);
      const { error } = await client.from("daily_report_attachments").delete().eq("id", attachment.id);
      if (error) throw error;
      setAttachments((current) => current.filter((item) => item.id !== attachment.id));
      setNotice("ลบไฟล์แนบแล้ว");
    } catch (error) {
      console.warn("GoodSeed attachment delete failed", error);
      setNotice(`ลบไฟล์ไม่สำเร็จ: ${supabaseAuthMessage(error)}`);
    }
  };

  const downloadAttachment = async (attachment) => {
    const client = getSupabaseClient({ silent: true });
    const itemBucket = attachment.metadata?.bucket || bucket;
    if (!client || !attachment.storage_path) {
      if (attachment.signed_url || attachment.file_url) window.open(attachment.signed_url || attachment.file_url, "_blank", "noopener,noreferrer");
      return;
    }
    const { data, error } = await client.storage.from(itemBucket).download(attachment.storage_path);
    if (error) {
      setNotice(`ดาวน์โหลดไม่สำเร็จ: ${supabaseAuthMessage(error)}`);
      return;
    }
    const url = URL.createObjectURL(data);
    const link = document.createElement("a");
    link.href = url;
    link.download = attachment.file_name || "daily-report-file";
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className={`${wide ? "md:col-span-2" : ""} rounded-lg border border-dashed border-goodseed-200 bg-white p-4`}>
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <h4 className="flex items-center gap-2 text-sm font-black text-goodseed-950"><Icon name="upload" className="h-4 w-4" />{title}</h4>
          <p className="mt-1 text-xs font-bold text-goodseed-600">รองรับ JPG, PNG, WEBP, PDF, DOC/DOCX, XLS/XLSX, CSV สูงสุด 20 MB ต่อไฟล์ และผูกกับ Report ID: {report?.report_code || report?.id || "จะสร้างอัตโนมัติเมื่ออัปโหลด"}</p>
        </div>
        {actions && <div className="flex flex-wrap gap-2">{actions}</div>}
      </div>
      <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_auto]">
        <Input label="คำอธิบายไฟล์แนบ" value={description} onChange={setDescription} />
        <div className="flex flex-wrap items-end gap-2">
          {sectionName === "owner-summary" && <>
            <button type="button" disabled={uploading} onClick={() => openPicker("photo")} className="inline-flex min-h-10 items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white hover:bg-goodseed-800 disabled:opacity-60"><Icon name="camera" className="h-4 w-4" />Attach Photos</button>
            <button type="button" disabled={uploading} onClick={() => openPicker("document")} className="inline-flex min-h-10 items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white hover:bg-goodseed-800 disabled:opacity-60"><Icon name="file" className="h-4 w-4" />Attach Documents</button>
          </>}
          {dailyReportFileGroups.map((group) => (
            <button key={group.id} type="button" disabled={uploading} onClick={() => openPicker(group.id)} className="inline-flex min-h-10 items-center justify-center gap-2 rounded-lg border border-goodseed-200 bg-goodseed-50 px-3 py-2 text-xs font-extrabold text-goodseed-800 hover:bg-goodseed-100 disabled:opacity-60">
              <Icon name={group.id === "photo" ? "camera" : group.id === "spreadsheet" ? "layout" : "file"} className="h-4 w-4" />
              {group.label}
            </button>
          ))}
        </div>
      </div>
      <input ref={inputRef} type="file" multiple accept={accept} onChange={uploadFiles} className="hidden" />
      {uploading && <div className="mt-3 rounded-lg bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-700">กำลังอัปโหลดไฟล์จริงเข้า Supabase Storage...</div>}
      {notice && <div className="mt-3 rounded-lg border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-800">{notice}</div>}
      <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
        {attachments.map((attachment) => {
          const isImage = String(attachment.file_type || "").startsWith("image/");
          const openUrl = attachment.signed_url || attachment.file_url;
          const canDelete = canManageFiles || attachment.uploaded_by === currentUserId;
          return (
            <div key={attachment.id} className="overflow-hidden rounded-lg border border-goodseed-100 bg-goodseed-50">
              {isImage && openUrl ? <img src={openUrl} alt={attachment.file_name} className="h-36 w-full object-cover" /> : <div className="grid h-24 place-items-center bg-white text-goodseed-700"><Icon name="file" className="h-8 w-8" /></div>}
              <div className="space-y-2 p-3">
                <p className="truncate text-sm font-black text-goodseed-950">{attachment.file_name}</p>
                <div className="flex flex-wrap gap-2 text-xs font-bold text-goodseed-700">
                  <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{attachment.file_type || fileExtension(attachment.file_name)}</Badge>
                  <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{formatFileSize(attachment.file_size)}</Badge>
                  <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{dailyReportAttachmentStatusLabels[attachment.status] || attachment.status}</Badge>
                </div>
                {attachment.description && <p className="text-xs font-semibold text-goodseed-700">{attachment.description}</p>}
                <div className="flex flex-wrap gap-2">
                  {openUrl && <button type="button" onClick={() => window.open(openUrl, "_blank", "noopener,noreferrer")} className="inline-flex items-center gap-1 rounded-lg bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-50"><Icon name="file" className="h-4 w-4" />เปิดดู</button>}
                  <button type="button" onClick={() => downloadAttachment(attachment)} className="inline-flex items-center gap-1 rounded-lg bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-50"><Icon name="download" className="h-4 w-4" />ดาวน์โหลด</button>
                  {canDelete && <button type="button" onClick={() => deleteAttachment(attachment)} className="inline-flex items-center gap-1 rounded-lg bg-red-50 px-3 py-2 text-xs font-extrabold text-red-700 ring-1 ring-red-100 hover:bg-red-100"><Icon name="trash" className="h-4 w-4" />ลบ</button>}
                </div>
              </div>
            </div>
          );
        })}
      </div>
      {!attachments.length && <p className="mt-3 rounded-lg bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-700">ยังไม่มีไฟล์แนบในหัวข้อนี้</p>}
    </div>
  );
}

function FormSection({ title, subtitle, children }) {
  return (
    <div className="rounded-lg border border-goodseed-100 bg-goodseed-50/60 p-4">
      <div className="mb-4">
        <h3 className="text-lg font-extrabold text-goodseed-950">{title}</h3>
        <p className="mt-1 text-sm font-semibold text-goodseed-700">{subtitle}</p>
      </div>
      <div className="grid gap-4 md:grid-cols-2">{children}</div>
    </div>
  );
}

function WeatherReportCard({ weather, loading, form, update, language = "th" }) {
  const [activeWeatherPanel, setActiveWeatherPanel] = useState(null);
  const [historyRows, setHistoryRows] = useState(readWeatherHistory);
  const [historyDate, setHistoryDate] = useState("");
  const isEn = language === "en";
  const weatherCopy = {
    title: isEn ? "Today's Weather" : "สภาพอากาศวันนี้",
    location: isEn ? `${farmWeatherLocation.nameEn} | ${farmWeatherLocation.labelEn}` : `${farmWeatherLocation.name} | ${farmWeatherLocation.label}`,
    locationNote: isEn ? `Uses farm location only, not the user's device location ${loading ? "(updating...)" : ""}` : `ใช้ตำแหน่งฟาร์มเท่านั้น ไม่ใช้ตำแหน่งผู้ใช้งาน ${loading ? "(กำลังอัปเดต...)" : ""}`,
    forecastButton: isEn ? "Forecast" : "พยากรณ์ล่วงหน้า",
    historyButton: isEn ? "History" : "บันทึกย้อนหลัง",
    forecastTitle: isEn ? "3-7 Day Forecast" : "พยากรณ์ล่วงหน้า 3-7 วัน",
    forecastSubtitle: isEn ? "Rain chance, temperature, wind, humidity and farm work recommendations" : "โอกาสฝน อุณหภูมิ ลม ความชื้น และคำแนะนำงานฟาร์ม",
    rain: isEn ? "Rain" : "ฝน",
    temperature: isEn ? "Temperature" : "อุณหภูมิ",
    wind: isEn ? "Wind" : "ลม",
    humidity: isEn ? "Humidity" : "ความชื้น",
    historyTitle: isEn ? "Weather History" : "บันทึกย้อนหลังสภาพอากาศ",
    historySubtitle: isEn ? "Saved Weather Module snapshots for farm work review" : "บันทึก snapshot จาก Weather Module เพื่อใช้ตรวจสอบงานย้อนหลัง",
    dateFilter: isEn ? "Select Date" : "เลือกวันที่",
    all: isEn ? "All" : "ทั้งหมด",
    graphTitle: isEn ? "History Chart: Temperature and Rain Chance" : "กราฟย้อนหลัง: อุณหภูมิและโอกาสฝน",
    noHistory: isEn ? "No weather history for the selected date." : "ยังไม่มีบันทึกย้อนหลังสำหรับวันที่เลือก",
    condition: isEn ? ({ "เมฆมาก": "Cloudy", "มีฝน": "Rain", "มีเมฆบางส่วน": "Partly cloudy" }[weather.condition] || weather.condition) : weather.condition,
    adviceTitle: isEn ? "Daily farm alerts and recommendations" : "แจ้งเตือนและคำแนะนำงานฟาร์มประจำวัน",
    updatedAt: isEn ? "Last Updated" : "อัปเดตล่าสุด",
    highLow: isEn ? "High / Low" : "สูงสุด / ต่ำสุด",
    rainAmount: isEn ? "Rain Chance / Amount" : "โอกาสฝน / ปริมาณฝน",
    windDirection: isEn ? "Wind / Direction" : "ลม / ทิศทางลม",
    uvIndex: isEn ? "UV Index" : "ดัชนี UV",
    pressure: isEn ? "Pressure" : "ความกดอากาศ",
    cloudCover: isEn ? "Cloud Cover" : "สภาพเมฆ",
    waterQuestion: isEn ? "Should we irrigate today?" : "วันนี้ควรรดน้ำหรือไม่",
    plantingQuestion: isEn ? "Is today suitable for planting?" : "วันนี้เหมาะกับการปลูกหรือไม่",
    sprayQuestion: isEn ? "Should we spray fertilizer/pesticide?" : "ควรพ่นปุ๋ย/พ่นยาหรือไม่",
    soilCondition: isEn ? "Actual Soil Condition" : "สภาพดินจริงในแปลง",
    standingWater: isEn ? "Standing Water" : "มีน้ำขังหรือไม่",
    fieldNote: isEn ? "Field Weather Note" : "หมายเหตุจากหน้างาน",
    weatherPhoto: isEn ? "Weather or Field Condition Photo" : "รูปภาพประกอบสภาพอากาศหรือสภาพแปลง",
  };
  const advice = getWeatherAdvice(weather);
  const forecastRows = weather.forecastRows?.length ? weather.forecastRows : createFallbackForecastRows(weather);
  const filteredHistoryRows = historyRows.filter((row) => !historyDate || row.date === historyDate);
  const riskTone = advice.risks.some((risk) => risk.includes("ฝนตกหนัก") || risk.includes("ลมแรง")) ? "border-red-200 bg-red-50" : advice.risks.some((risk) => risk.includes("UV")) ? "border-amber-200 bg-amber-50" : "border-goodseed-100 bg-goodseed-50";
  const forecastAdviceText = (row) => {
    if (!isEn) return row.advice;
    if (row.rainChance >= 60) return "Reduce irrigation and avoid spraying.";
    if (row.uvIndex >= 8 || row.maxTemp >= 35) return "Schedule outdoor work in the morning or evening.";
    return "Farm work can proceed as planned.";
  };
  const adviceText = (text) => {
    if (!isEn) return text;
    const map = {
      "มีโอกาสฝน ควรลดรอบรดน้ำ": "Rain is possible. Reduce irrigation rounds.",
      "อากาศร้อน ควรรดน้ำช่วงเช้าหรือเย็น": "Hot weather. Irrigate in the morning or evening.",
      "รดน้ำตามแผนปกติ": "Irrigate as planned.",
      "แดดแรง ควรปลูกช่วงเช้าหรือเย็น": "Strong sun. Plant in the morning or evening.",
      "เหมาะกับการปลูกและย้ายกล้า": "Suitable for planting and transplanting.",
      "หลีกเลี่ยงการพ่นปุ๋ย/พ่นยา": "Avoid fertilizer or pesticide spraying.",
      "พ่นได้ แต่ควรติดตามลมก่อนเริ่มงาน": "Spraying is possible. Check wind before starting.",
      "ตรวจความชื้นดินก่อนรดน้ำ และวางงานพ่นช่วงลมนิ่ง": "Check soil moisture before irrigation and schedule spraying when wind is calm.",
      "ไม่มีความเสี่ยงรุนแรง": "No major risk.",
      "เสี่ยงฝนตกหนัก": "Heavy rain risk.",
      "เสี่ยงลมแรง": "Strong wind risk.",
      "UV สูง ระวังแดดจัด": "High UV. Avoid strong sun exposure.",
    };
    return map[text] || text;
  };
  const formatForecastLabel = (date) => new Date(`${date}T00:00:00+07:00`).toLocaleDateString(isEn ? "en-US" : "th-TH", { weekday: "short", day: "numeric", month: "short" });
  const refreshHistory = () => {
    const nextRows = addWeatherHistoryRecord(weather);
    setHistoryRows(nextRows);
  };
  const exportWeatherCsv = () => {
    const header = isEn ? ["Date", "Time", "Temperature", "Rain Chance", "Humidity", "Wind", "Condition", "Advice"] : ["วันที่", "เวลา", "อุณหภูมิ", "โอกาสฝน", "ความชื้น", "ลม", "สภาพอากาศ", "คำแนะนำ"];
    const rows = filteredHistoryRows.map((row) => [row.date, row.time, row.temperature, row.rainChance, row.humidity, row.windSpeed, row.condition, row.advice]);
    downloadFile("goodseed-weather-history.csv", "\ufeff" + [header, ...rows].map((row) => row.map((cell) => `"${String(cell ?? "").replaceAll('"', '""')}"`).join(",")).join("\n"), "text/csv;charset=utf-8");
  };
  const exportWeatherPdf = () => {
    const html = `<html><meta charset="utf-8"><body><h1>${weatherCopy.historyTitle}</h1><p>${weatherCopy.location}</p><table border="1" cellspacing="0" cellpadding="6"><tr><th>${isEn ? "Date" : "วันที่"}</th><th>${isEn ? "Time" : "เวลา"}</th><th>${isEn ? "Temp" : "อุณหภูมิ"}</th><th>${isEn ? "Rain" : "ฝน"}</th><th>${weatherCopy.humidity}</th><th>${weatherCopy.wind}</th><th>${isEn ? "Condition" : "สภาพ"}</th><th>${isEn ? "Advice" : "คำแนะนำ"}</th></tr>${filteredHistoryRows.map((row) => `<tr><td>${row.date}</td><td>${row.time}</td><td>${row.temperature} C</td><td>${row.rainChance}%</td><td>${row.humidity}%</td><td>${row.windSpeed} km/h</td><td>${row.condition}</td><td>${row.advice}</td></tr>`).join("")}</table></body></html>`;
    downloadFile("goodseed-weather-history-pdf.html", html, "text/html;charset=utf-8");
  };
  return (
    <div className={`rounded-lg border p-4 ${riskTone}`}>
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="min-w-0">
          <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
            <div>
              <h3 className="text-2xl font-extrabold text-goodseed-950">{weatherCopy.title}</h3>
              <p className="mt-1 text-sm font-extrabold text-goodseed-700">{weatherCopy.location}</p>
            </div>
            <div className="flex flex-col gap-2 sm:flex-row">
              <button type="button" onClick={() => setActiveWeatherPanel(activeWeatherPanel === "forecast" ? null : "forecast")} className={`inline-flex min-h-11 items-center justify-center gap-2 rounded-full px-4 py-2 text-sm font-black ring-1 transition ${activeWeatherPanel === "forecast" ? "bg-goodseed-700 text-white ring-goodseed-700" : "bg-white text-goodseed-800 ring-goodseed-100 hover:bg-goodseed-50"}`}><Icon name="cloud-sun" className="h-4 w-4" />{weatherCopy.forecastButton}</button>
              <button type="button" onClick={() => { refreshHistory(); setActiveWeatherPanel(activeWeatherPanel === "history" ? null : "history"); }} className={`inline-flex min-h-11 items-center justify-center gap-2 rounded-full px-4 py-2 text-sm font-black ring-1 transition ${activeWeatherPanel === "history" ? "bg-goodseed-700 text-white ring-goodseed-700" : "bg-white text-goodseed-800 ring-goodseed-100 hover:bg-goodseed-50"}`}><Icon name="calendar-clock" className="h-4 w-4" />{weatherCopy.historyButton}</button>
            </div>
          </div>
          <p className="mt-1 text-sm font-semibold text-goodseed-700">{weatherCopy.locationNote}</p>
        </div>
        <div className="flex items-center gap-4 rounded-lg bg-white p-4 shadow-sm">
          <div className="grid h-16 w-16 place-items-center rounded-full bg-goodseed-100 text-goodseed-800"><Icon name="cloud-sun" className="h-8 w-8" /></div>
          <div><p className="text-4xl font-extrabold text-goodseed-950">{Math.round(weather.temperature)} C</p><p className="font-bold text-goodseed-700">{weatherCopy.condition}</p></div>
        </div>
      </div>
      {activeWeatherPanel === "forecast" && (
        <div className="mt-4 rounded-xl border border-goodseed-100 bg-white p-4 shadow-sm">
          <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
            <div>
              <h4 className="text-lg font-black text-goodseed-950">{weatherCopy.forecastTitle}</h4>
              <p className="mt-1 text-sm font-bold text-goodseed-600">{weatherCopy.forecastSubtitle}</p>
            </div>
            <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Auto update</Badge>
          </div>
          <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-7">
            {forecastRows.map((row) => (
              <div key={row.date} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-3">
                <p className="text-sm font-black text-goodseed-950">{formatForecastLabel(row.date)}</p>
                <div className="mt-3 space-y-2 text-xs font-bold text-goodseed-700">
                  <p>{weatherCopy.rain}: {row.rainChance}%</p>
                  <p>{weatherCopy.temperature}: {Math.round(row.maxTemp)} / {Math.round(row.minTemp)} C</p>
                  <p>{weatherCopy.wind}: {Math.round(row.windSpeed)} km/h</p>
                  <p>{weatherCopy.humidity}: {Math.round(row.humidity)}%</p>
                </div>
                <p className="mt-3 rounded-lg bg-white p-2 text-xs font-bold leading-5 text-goodseed-800">{forecastAdviceText(row)}</p>
              </div>
            ))}
          </div>
        </div>
      )}
      {activeWeatherPanel === "history" && (
        <div className="mt-4 rounded-xl border border-goodseed-100 bg-white p-4 shadow-sm">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
            <div>
              <h4 className="text-lg font-black text-goodseed-950">{weatherCopy.historyTitle}</h4>
              <p className="mt-1 text-sm font-bold text-goodseed-600">{weatherCopy.historySubtitle}</p>
            </div>
            <div className="grid gap-2 sm:grid-cols-[190px_auto_auto_auto]">
              <Input label={weatherCopy.dateFilter} type="date" value={historyDate} onChange={setHistoryDate} />
              <button type="button" onClick={() => setHistoryDate("")} className="self-end rounded-lg border border-goodseed-100 bg-white px-4 py-2.5 text-sm font-black text-goodseed-800">{weatherCopy.all}</button>
              <button type="button" onClick={exportWeatherCsv} className="self-end rounded-lg bg-goodseed-700 px-4 py-2.5 text-sm font-black text-white">Export CSV</button>
              <button type="button" onClick={exportWeatherPdf} className="self-end rounded-lg border border-goodseed-200 bg-white px-4 py-2.5 text-sm font-black text-goodseed-800">Export PDF</button>
            </div>
          </div>
          <div className="mt-4 grid gap-3 md:grid-cols-4">
            {filteredHistoryRows.slice(0, 4).map((row) => (
              <div key={row.id} className="rounded-xl bg-goodseed-50 p-3">
                <p className="text-xs font-black text-goodseed-600">{row.date} {row.time}</p>
                <p className="mt-1 text-2xl font-black text-goodseed-950">{row.temperature} C</p>
                <p className="mt-1 text-xs font-bold text-goodseed-700">{weatherCopy.rain} {row.rainChance}% / {weatherCopy.humidity} {row.humidity}%</p>
              </div>
            ))}
          </div>
          <div className="mt-4 rounded-xl bg-goodseed-50 p-4">
            <p className="text-sm font-black text-goodseed-950">{weatherCopy.graphTitle}</p>
            <div className="mt-3 grid h-36 grid-cols-7 items-end gap-2">
              {filteredHistoryRows.slice(0, 7).reverse().map((row) => (
                <div key={`graph-${row.id}`} className="flex h-full flex-col justify-end gap-1">
                  <div className="rounded-t bg-goodseed-700" style={{ height: `${Math.max(12, Math.min(100, row.temperature * 2.2))}%` }} />
                  <div className="rounded-t bg-blue-400" style={{ height: `${Math.max(8, Math.min(100, row.rainChance))}%` }} />
                  <p className="truncate text-center text-[10px] font-bold text-goodseed-700">{row.time}</p>
                </div>
              ))}
            </div>
          </div>
          <div className="mt-4 thin-scrollbar overflow-x-auto rounded-xl border border-goodseed-100">
            <table className="min-w-[820px] w-full text-left text-sm">
              <thead className="bg-goodseed-50 text-goodseed-800"><tr>{(isEn ? ["Date", "Time", "Temperature", "Rain", "Humidity", "Wind", "Condition", "Advice"] : ["วันที่", "เวลา", "อุณหภูมิ", "ฝน", "ความชื้น", "ลม", "สภาพ", "คำแนะนำ"]).map((head) => <th key={head} className="px-3 py-3 font-black">{head}</th>)}</tr></thead>
              <tbody className="divide-y divide-goodseed-100 bg-white">
                {filteredHistoryRows.map((row) => (
                  <tr key={row.id}><td className="px-3 py-3 font-bold">{row.date}</td><td className="px-3 py-3">{row.time}</td><td className="px-3 py-3 font-black">{row.temperature} C</td><td className="px-3 py-3">{row.rainChance}%</td><td className="px-3 py-3">{row.humidity}%</td><td className="px-3 py-3">{row.windSpeed} km/h</td><td className="px-3 py-3">{row.condition}</td><td className="px-3 py-3">{row.advice}</td></tr>
                ))}
              </tbody>
            </table>
          </div>
          {filteredHistoryRows.length === 0 && <p className="mt-4 rounded-lg bg-amber-50 p-3 text-sm font-bold text-amber-800">{weatherCopy.noHistory}</p>}
        </div>
      )}
      <div className="mt-5 grid gap-3 md:grid-cols-4">
        <MiniMetric label={weatherCopy.highLow} value={`${Math.round(weather.maxTemp)} / ${Math.round(weather.minTemp)} C`} />
        <MiniMetric label={weatherCopy.humidity} value={`${weather.humidity}%`} />
        <MiniMetric label={weatherCopy.rainAmount} value={`${weather.rainChance}% / ${weather.rainAmount} ${isEn ? "mm" : "มม."}`} danger={weather.rainChance >= 60} />
        <MiniMetric label={weatherCopy.windDirection} value={`${weather.windSpeed} km/h ${weather.windDirection}`} danger={weather.windSpeed >= 20} />
        <MiniMetric label={weatherCopy.uvIndex} value={weather.uvIndex} danger={weather.uvIndex >= 8} />
        <MiniMetric label={weatherCopy.pressure} value={`${Math.round(weather.pressure)} hPa`} />
        <MiniMetric label={weatherCopy.cloudCover} value={`${weather.cloudCover}%`} />
        <MiniMetric label={weatherCopy.updatedAt} value={weather.updatedAt} />
      </div>
      <div className="mt-5 grid gap-3 md:grid-cols-3">
        {[[weatherCopy.waterQuestion, advice.water], [weatherCopy.plantingQuestion, advice.planting], [weatherCopy.sprayQuestion, advice.spray]].map(([label, item]) => (
          <div key={label} className="rounded-lg bg-white p-3 ring-1 ring-goodseed-100">
            <div className="flex items-center justify-between gap-2"><p className="text-sm font-extrabold text-goodseed-900">{label}</p><RiskBadge status={item[0]} language={language} /></div>
            <p className="mt-2 text-xs font-bold text-goodseed-700">{adviceText(item[1])}</p>
          </div>
        ))}
      </div>
      <div className="mt-4 rounded-lg bg-white p-3 ring-1 ring-goodseed-100">
        <p className="text-sm font-extrabold text-goodseed-900">{weatherCopy.adviceTitle}</p>
        <p className="mt-1 text-sm font-semibold text-goodseed-700">{advice.risks.map(adviceText).join(" / ")} | {adviceText(advice.daily)}</p>
      </div>
      <div className="mt-5 grid gap-4 md:grid-cols-2">
        <Select label={weatherCopy.soilCondition} value={form.soilCondition} onChange={(value) => update("soilCondition", value)} options={["ดินแห้ง", "ดินชื้น", "ดินแฉะ"]} />
        <Select label={weatherCopy.standingWater} value={form.standingWater} onChange={(value) => update("standingWater", value)} options={["ไม่มีน้ำขัง", "มีน้ำขังเล็กน้อย", "มีน้ำขังมาก"]} />
        <Textarea label={weatherCopy.fieldNote} value={form.fieldWeatherNote} onChange={(value) => update("fieldWeatherNote", value)} />
        <UploadBox label={weatherCopy.weatherPhoto} value={form.weatherPhoto} onChange={(value) => update("weatherPhoto", value)} />
      </div>
    </div>
  );
}

function ManagerReportQrPanel() {
  const buildInitialQrImages = () => {
    const saved = readManagerReportQrState();
    const hiddenOriginalIds = Array.isArray(saved.hiddenOriginalIds) ? saved.hiddenOriginalIds : [];
    const customImages = Array.isArray(saved.customImages) ? saved.customImages : [];

    return [
      ...customImages,
      ...managerReportQrImages
        .filter((item) => !hiddenOriginalIds.includes(item.src))
        .map((item) => ({ ...item, id: item.src, source: "ต้นฉบับ", original: true })),
    ];
  };

  const [qrImages, setQrImages] = useState(buildInitialQrImages);
  const [preview, setPreview] = useState(null);
  const [message, setMessage] = useState("");

  const persistQrImages = (nextImages, nextHiddenOriginalIds) => {
    const saved = readManagerReportQrState();
    const hiddenOriginalIds = nextHiddenOriginalIds || (Array.isArray(saved.hiddenOriginalIds) ? saved.hiddenOriginalIds : []);

    writeManagerReportQrState({
      hiddenOriginalIds,
      customImages: nextImages.filter((item) => item.custom),
    });
  };

  const readFileAsDataUrl = (file) => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });

  const handleAddQrImages = async (event) => {
    const files = Array.from(event.target.files || []);
    if (!files.length) return;

    setMessage("กำลังเพิ่มรูปภาพ QR...");

    try {
      const uploadedImages = await Promise.all(files.map(async (file, index) => ({
        id: `uploaded-qr-${Date.now()}-${index}-${file.name}`,
        title: file.name.replace(/\.[^.]+$/, "") || "QR Code ใหม่",
        src: await readFileAsDataUrl(file),
        area: "เพิ่มจากไฟล์รูปภาพ",
        source: "เพิ่มใหม่",
        fileName: file.name,
        custom: true,
      })));

      setQrImages((current) => {
        const nextImages = [...uploadedImages, ...current];
        persistQrImages(nextImages);
        return nextImages;
      });
      setMessage(`เพิ่มรูปภาพ QR แล้ว ${uploadedImages.length} ไฟล์`);
    } catch (error) {
      setMessage("ไม่สามารถเพิ่มรูปภาพ QR ได้ กรุณาลองใหม่");
    }

    event.target.value = "";
  };

  const handleRemoveQrImage = (item) => {
    if (!window.confirm(`ต้องการลบรูปภาพ QR "${item.title}" หรือไม่`)) return;
    setQrImages((current) => {
      const nextImages = current.filter((qr) => qr.id !== item.id);
      const saved = readManagerReportQrState();
      const existingHiddenOriginalIds = Array.isArray(saved.hiddenOriginalIds) ? saved.hiddenOriginalIds : [];
      const hiddenOriginalIds = item.original
        ? Array.from(new Set([...existingHiddenOriginalIds, item.src]))
        : existingHiddenOriginalIds;

      persistQrImages(nextImages, hiddenOriginalIds);
      return nextImages;
    });
    if (preview?.id === item.id) setPreview(null);
    setMessage("ลบรูปภาพ QR แล้ว");
  };

  const handleRestoreOriginalQrImages = () => {
    const nextImages = [
      ...qrImages.filter((item) => item.custom),
      ...managerReportQrImages.map((item) => ({ ...item, id: item.src, source: "ต้นฉบับ", original: true })),
    ];

    setQrImages(nextImages);
    writeManagerReportQrState({
      hiddenOriginalIds: [],
      customImages: nextImages.filter((item) => item.custom),
    });
    setMessage("คืนค่ารูป QR ต้นฉบับแล้ว");
  };

  return (
    <div className="mb-6 rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
      <div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h3 className="font-extrabold text-goodseed-900">QR Code สำหรับสแกนส่งรายงานผู้จัดการ</h3>
          <p className="mt-1 text-sm text-goodseed-700">ใช้รูปต้นฉบับตามที่แนบมา เพื่อให้ทีมงานสแกนเข้าฟอร์มได้ทันที และเพิ่มรูป QR ใหม่ได้จากไฟล์รูปภาพ</p>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {message && <Badge className="bg-white text-goodseed-800 ring-goodseed-200">{message}</Badge>}
          <button type="button" onClick={handleRestoreOriginalQrImages} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800 shadow-sm transition hover:bg-goodseed-50">
            <Icon name="refresh" className="h-4 w-4" />
            คืนค่าต้นฉบับ
          </button>
          <label className="inline-flex cursor-pointer items-center gap-2 rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white shadow-sm transition hover:bg-goodseed-800">
            <Icon name="upload" className="h-4 w-4" />
            เพิ่มรูปภาพ QR
            <input type="file" accept="image/*" multiple className="hidden" onChange={handleAddQrImages} />
          </label>
        </div>
      </div>
      <div className="thin-scrollbar flex gap-4 overflow-x-auto pb-2">
        {qrImages.map((item) => (
          <article
            key={item.id}
            className="group w-64 shrink-0 overflow-hidden rounded-lg border border-goodseed-100 bg-white shadow-sm transition hover:-translate-y-0.5 hover:border-goodseed-400 hover:shadow-soft"
          >
            <button type="button" onClick={() => setPreview(item)} className="grid h-44 w-full place-items-center bg-white p-2">
              <img src={item.src} alt={item.title} className="max-h-full max-w-full object-contain" loading="lazy" />
            </button>
            <div className="border-t border-goodseed-100 p-3">
              <div className="flex items-start justify-between gap-2">
                <div className="min-w-0">
                  <p className="truncate text-sm font-extrabold text-goodseed-900">{item.title}</p>
                  <p className="mt-1 text-xs font-bold text-goodseed-600">{item.area}</p>
                </div>
                <Badge className={item.custom ? "bg-blue-50 text-blue-700 ring-blue-200" : "bg-goodseed-50 text-goodseed-700 ring-goodseed-100"}>{item.source}</Badge>
              </div>
              <div className="mt-3 flex gap-2">
                <button type="button" onClick={() => setPreview(item)} className="flex-1 rounded-lg bg-goodseed-50 px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-100">ดูรูป</button>
                <button type="button" onClick={() => handleRemoveQrImage(item)} className="flex-1 rounded-lg bg-red-50 px-3 py-2 text-xs font-extrabold text-red-700 ring-1 ring-red-100 transition hover:bg-red-100">ลบ</button>
              </div>
            </div>
          </article>
        ))}
      </div>
      {preview && (
        <div className="fixed inset-0 z-50 grid place-items-center bg-goodseed-950/70 p-4" role="dialog" aria-modal="true">
          <div className="w-full max-w-3xl overflow-hidden rounded-2xl bg-white shadow-2xl">
            <div className="flex items-center justify-between gap-3 border-b border-goodseed-100 p-4">
              <div>
                <p className="text-lg font-extrabold text-goodseed-950">{preview.title}</p>
                <p className="text-sm font-bold text-goodseed-600">{preview.area}</p>
              </div>
              <button type="button" onClick={() => setPreview(null)} className="grid h-10 w-10 place-items-center rounded-full bg-goodseed-50 text-goodseed-800 transition hover:bg-goodseed-100">
                <Icon name="x" className="h-5 w-5" />
              </button>
            </div>
            <div className="grid max-h-[75vh] place-items-center overflow-auto bg-white p-4">
              <img src={preview.src} alt={preview.title} className="max-h-[68vh] max-w-full object-contain" />
            </div>
            <div className="flex flex-wrap justify-end gap-2 border-t border-goodseed-100 p-4">
              <a href={preview.src} target="_blank" rel="noreferrer" className="rounded-lg border border-goodseed-200 px-4 py-2 text-sm font-extrabold text-goodseed-800 transition hover:bg-goodseed-50">{preview.original ? "เปิดรูปต้นฉบับ" : "เปิดรูป"}</a>
              <button type="button" onClick={() => handleRemoveQrImage(preview)} className="rounded-lg bg-red-600 px-4 py-2 text-sm font-extrabold text-white transition hover:bg-red-700">ลบรูปภาพ QR</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function Input({ label, value, onChange, type = "text" }) {
  return <label><span className="text-sm font-bold text-goodseed-800">{label}</span><input type={type} value={value} onChange={(event) => onChange(event.target.value)} className="mt-2 w-full rounded-lg border border-goodseed-200 bg-white px-3 py-2.5 text-sm text-goodseed-900 outline-none focus:ring-2 focus:ring-goodseed-300" /></label>;
}

function Select({ label, value, onChange, options }) {
  return <label><span className="text-sm font-bold text-goodseed-800">{label}</span><select value={value} onChange={(event) => onChange(event.target.value)} className="mt-2 w-full rounded-lg border border-goodseed-200 bg-white px-3 py-2.5 text-sm text-goodseed-900 outline-none focus:ring-2 focus:ring-goodseed-300">{options.map((option) => <option key={option}>{option}</option>)}</select></label>;
}

function Textarea({ label, value, onChange, wide }) {
  return <label className={wide ? "md:col-span-2" : ""}><span className="text-sm font-bold text-goodseed-800">{label}</span><textarea value={value} onChange={(event) => onChange(event.target.value)} rows="3" className="mt-2 w-full resize-none rounded-lg border border-goodseed-200 bg-white px-3 py-2.5 text-sm text-goodseed-900 outline-none focus:ring-2 focus:ring-goodseed-300" /></label>;
}

function UploadBox({ label, value, onChange }) {
  return (
    <label className="rounded-lg border-2 border-dashed border-goodseed-200 bg-goodseed-50 p-4">
      <span className="flex items-center gap-2 text-sm font-bold text-goodseed-800"><Icon name="upload" className="h-4 w-4" />{label}</span>
      <input value={value} onChange={(event) => onChange(event.target.value)} className="mt-3 w-full rounded-lg border border-goodseed-200 bg-white px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-goodseed-300" />
    </label>
  );
}

const crudGrowthMessage = "ระบบนี้ออกแบบให้รองรับการเติบโตของฟาร์มในอนาคต ทุกข้อมูลสามารถเพิ่ม แก้ไข หรือปิดการใช้งานได้ตามการใช้งานจริง โดยยังคงเก็บประวัติย้อนหลังเพื่อความโปร่งใสและตรวจสอบได้";

const crudModules = [
  { id: "employees", route: "people-hr", icon: "users", title: "Employees / พนักงาน", policy: "Soft Delete เมื่อพนักงานลาออก", sample: ["คุณหวาน", "พี่ไกร", "พี่สมชาย"], fields: ["ชื่อ-นามสกุล", "ชื่อเล่น", "ตำแหน่ง", "เบอร์โทร", "วันที่เริ่มงาน", "วันที่ลาออก", "สถานะ", "สิทธิ์", "รูปถ่าย", "หมายเหตุ"] },
  { id: "inventory", route: "inventory", icon: "box", title: "Inventory / Warehouse", policy: "เพิ่มวัสดุ หมวด หน่วยนับ และอื่น ๆ ระบุเอง", sample: ["ปุ๋ยอินทรีย์", "ไบโอชา", "น้ำมันดีเซล"], fields: ["หมวดหมู่", "ชื่อรายการ", "อื่น ๆ / ระบุเอง", "หน่วยนับ", "Minimum Stock", "สถานะ"] },
  { id: "equipment", route: "equipment", icon: "assets", title: "Equipment & Vehicle", policy: "Inactive เมื่อขาย ชำรุด หรือเลิกใช้", sample: ["รถกระบะ", "เครื่องตัดหญ้า", "ปั๊มน้ำ"], fields: ["Asset ID", "ชื่ออุปกรณ์", "ประเภท", "Serial Number", "ผู้รับผิดชอบ", "รอบตรวจ", "สถานะ"] },
  { id: "farm-plots", route: "farm-management", icon: "map", title: "Farm Plots / แปลงปลูก", policy: "ลบถาวรได้เฉพาะยังไม่มีข้อมูลผูกอยู่", sample: ["รอบปลูก A", "รอบปลูก B", "Zone 6"], fields: ["ชื่อแปลง", "โซน", "แถว", "รอบปลูก", "พื้นที่", "GPS Zone", "สถานะ"] },
  { id: "tree-database", route: "tree-management", icon: "tree", title: "Crop / Tree Database", policy: "ปิดใช้งานชนิดพืชที่ไม่ได้ปลูกแล้ว", sample: ["จามจุรีสีทอง", "หางนกยูง", "สะเดา"], fields: ["ชนิดต้นไม้", "สายพันธุ์", "ขนาด", "QR Tree ID", "สถานะ", "อื่น ๆ / ระบุเอง"] },
  { id: "rd-experiment", route: "experiment-rd", icon: "leaf", title: "R&D Experiment", policy: "เก็บผลทดลองเดิมไว้เมื่อยกเลิก", sample: ["มันญี่ปุ่น 4 สายพันธุ์", "Biochar Trial", "Azolla System"], fields: ["ชื่อการทดลอง", "ชุดทดลอง", "รูปแบบทดลอง", "ผู้รับผิดชอบ", "สถานะ", "ผลลัพธ์"] },
  { id: "work-plan", route: "daily-work", icon: "calendar", title: "Work Plan / Calendar", policy: "เพิ่มประเภทงานและสถานะงานใหม่ได้", sample: ["ตรวจแปลง", "ประชุม", "วันจ่ายเงินเดือน"], fields: ["วันที่", "ประเภทงาน", "หัวข้องาน", "ผู้รับผิดชอบ", "สถานะ", "หลักฐาน"] },
  { id: "finance", route: "finance", icon: "money", title: "Finance", policy: "รายการการเงินห้ามลบถาวร ใช้ Inactive เพื่อเก็บประวัติย้อนหลังและ Audit Log ทุกครั้ง", sample: ["ค่าแรง", "ค่าวัสดุปลูก", "รายรับไม้ล้อม"], fields: ["หมวดค่าใช้จ่าย", "รายการ", "จำนวนเงิน", "ผู้อนุมัติ", "หลักฐาน", "เหตุผลแก้ไข"] },
  { id: "forms-reports", route: "daily-report", icon: "file", title: "Forms / Reports", policy: "ปิดแบบฟอร์มที่ไม่ใช้แล้วโดยไม่ลบประวัติ", sample: ["รายงานประจำวัน", "ตรวจแปลง", "ฟอร์ม QR"], fields: ["ชื่อฟอร์ม", "Section", "คำถาม", "ช่องกรอกเอง", "สถานะ", "สิทธิ์"] },
  { id: "roles-access", route: "settings", icon: "shield", title: "User Roles / Access Control", policy: "Owner เท่านั้นที่ลบหรือกู้คืนสิทธิ์สำคัญ", sample: ["Owner", "Manager", "Staff"], fields: ["ชื่อ Role", "Module Permission", "สถานะบัญชี", "เหตุผลแก้ไข", "ผู้อนุมัติ"] },
];

const crudStatusOptions = ["Active", "Inactive", "Archived", "Deleted by Owner"];

function crudModuleById(moduleId) {
  return crudModules.find((module) => module.id === moduleId) || crudModules[0];
}

function canCrud(role, action, moduleId) {
  if (isOwnerRole(role) || role === "developer") return true;
  if (role === "admin") return action !== "restore" && !(action === "delete" && ["finance", "employees", "roles-access"].includes(moduleId));
  if (role === "manager") return ["add", "edit", "inactive", "export"].includes(action) && !["roles-access"].includes(moduleId);
  if (role === "staff") return action === "add" && ["inventory", "forms-reports", "work-plan", "rd-experiment"].includes(moduleId);
  return false;
}

function createAuditLog({ role, moduleId, action, itemName, oldValue, newValue, reason }) {
  const module = crudModuleById(moduleId);
  return {
    id: `LOG-${Date.now()}`,
    time: new Date().toLocaleString("th-TH", { dateStyle: "medium", timeStyle: "short" }),
    actor: roleInfo(role).label,
    module: module.title,
    action,
    itemName,
    oldValue: oldValue || "-",
    newValue: newValue || "-",
    reason: reason || "ปรับปรุงข้อมูลตามการใช้งานจริง",
  };
}

function CrudToast({ message, onClose }) {
  if (!message) return null;
  return (
    <div className="fixed bottom-5 right-5 z-[120] max-w-sm rounded-lg border border-goodseed-200 bg-white p-4 text-sm font-extrabold text-goodseed-900 shadow-2xl">
      <div className="flex items-start gap-3">
        <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-goodseed-100 text-goodseed-800"><Icon name="check" className="h-4 w-4" /></span>
        <div className="min-w-0 flex-1">{message}</div>
        <button onClick={onClose} className="text-goodseed-500"><Icon name="x" className="h-4 w-4" /></button>
      </div>
    </div>
  );
}

function CrudConfirmDialog({ confirm, onCancel, onConfirm }) {
  if (!confirm) return null;
  return (
    <div className="fixed inset-0 z-[110] grid place-items-center bg-goodseed-950/45 p-4 backdrop-blur-sm">
      <div className="w-full max-w-md rounded-2xl border border-goodseed-100 bg-white p-5 shadow-2xl">
        <div className="flex items-start gap-3">
          <div className="grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-red-50 text-red-700"><Icon name="trash" /></div>
          <div>
            <h3 className="text-lg font-black text-goodseed-950">ยืนยันการดำเนินการ</h3>
            <p className="mt-2 text-sm font-semibold leading-6 text-goodseed-700">{confirm.message}</p>
            <p className="mt-2 text-xs font-bold text-goodseed-500">ระบบจะบันทึก Audit Log ทุกครั้งเพื่อใช้ตรวจสอบย้อนหลัง</p>
          </div>
        </div>
        <div className="mt-5 flex justify-end gap-2">
          <button onClick={onCancel} className="rounded-lg border border-goodseed-100 bg-white px-4 py-2 text-sm font-black text-goodseed-800">ยกเลิก</button>
          <button onClick={onConfirm} className="rounded-lg bg-red-600 px-4 py-2 text-sm font-black text-white">ยืนยัน</button>
        </div>
      </div>
    </div>
  );
}

function CrudModalForm({ open, module, mode, itemName, onClose, onSave }) {
  const [form, setForm] = useState({
    name: itemName || "",
    category: module?.fields?.[0] || "",
    custom: "",
    status: "Active",
    detail: "",
    reason: "",
  });

  useEffect(() => {
    if (open) {
      setForm({
        name: itemName || "",
        category: module?.fields?.[0] || "",
        custom: "",
        status: "Active",
        detail: "",
        reason: "",
      });
    }
  }, [open, itemName, module?.id]);

  if (!open) return null;
  const update = (key, value) => setForm((current) => ({ ...current, [key]: value }));
  const categoryOptions = Array.from(new Set([...(module.fields || []), "อื่น ๆ / ระบุเอง"]));
  return (
    <div className="fixed inset-0 z-[105] grid place-items-center bg-goodseed-950/45 p-4 backdrop-blur-sm">
      <form onSubmit={(event) => { event.preventDefault(); onSave(form); }} className="thin-scrollbar max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-goodseed-100 bg-white p-5 shadow-2xl">
        <div className="flex items-start justify-between gap-4">
          <div>
            <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{mode === "edit" ? "แก้ไขรายการ" : "+ เพิ่มรายการใหม่"}</Badge>
            <h3 className="mt-3 text-2xl font-black text-goodseed-950">{module.title}</h3>
            <p className="mt-1 text-sm font-semibold text-goodseed-700">{module.policy}</p>
          </div>
          <button type="button" onClick={onClose} className="rounded-lg bg-goodseed-50 p-2 text-goodseed-800 ring-1 ring-goodseed-100"><Icon name="x" /></button>
        </div>
        <div className="mt-5 grid gap-4 md:grid-cols-2">
          <Input label="ชื่อรายการ" value={form.name} onChange={(value) => update("name", value)} />
          <Select label="หมวด / ประเภทข้อมูล" value={form.category} onChange={(value) => update("category", value)} options={categoryOptions} />
          {form.category === "อื่น ๆ / ระบุเอง" && <Input label="อื่น ๆ / ระบุเอง" value={form.custom} onChange={(value) => update("custom", value)} />}
          <Select label="สถานะรายการ" value={form.status} onChange={(value) => update("status", value)} options={crudStatusOptions} />
          <Textarea label="รายละเอียด / หมายเหตุ" value={form.detail} onChange={(value) => update("detail", value)} wide />
          <Textarea label="เหตุผลในการเพิ่มหรือแก้ไข" value={form.reason} onChange={(value) => update("reason", value)} wide />
        </div>
        <div className="mt-5 rounded-xl bg-goodseed-50 p-4 text-sm font-semibold leading-6 text-goodseed-800">
          {crudGrowthMessage}
        </div>
        <div className="mt-5 flex flex-col gap-2 sm:flex-row sm:justify-end">
          <button type="button" onClick={onClose} className="rounded-lg border border-goodseed-100 bg-white px-4 py-2 text-sm font-black text-goodseed-800">ยกเลิก</button>
          <button className="rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-black text-white">{mode === "edit" ? "บันทึกการแก้ไข" : "เพิ่มข้อมูลสำเร็จ"}</button>
        </div>
      </form>
    </div>
  );
}

function CrudActionMenu({ role, moduleId, itemName, onLog, onEdit, onInactive, onDelete }) {
  const [confirm, setConfirm] = useState(null);
  const module = crudModuleById(moduleId);
  const forceInactiveOnly = moduleId === "finance";
  const runAction = (action, label) => {
    const effectiveAction = forceInactiveOnly && action === "delete" ? "inactive" : action;
    const log = createAuditLog({
      role,
      moduleId,
      action: label,
      itemName,
      oldValue: effectiveAction === "edit" ? "ข้อมูลเดิม" : "Active",
      newValue: effectiveAction === "inactive" ? "Inactive" : effectiveAction === "delete" ? "Deleted by Owner" : "ข้อมูลใหม่",
      reason: `${label} ${itemName}`,
    });
    onLog?.(log);
    if (effectiveAction === "edit") onEdit?.();
    if (effectiveAction === "inactive") onInactive?.();
    if (effectiveAction === "delete") onDelete?.();
  };
  return (
    <div className="relative inline-flex flex-wrap gap-2">
      {canCrud(role, "edit", moduleId) && (
        <button onClick={() => runAction("edit", "แก้ไข")} className="inline-flex items-center gap-1 rounded-lg bg-white px-2.5 py-1.5 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-50">
          <Icon name="edit" className="h-3.5 w-3.5" />แก้ไข
        </button>
      )}
      {canCrud(role, "inactive", moduleId) && (
        <button onClick={() => setConfirm({ action: "inactive", message: `ต้องการปิดการใช้งาน "${itemName}" ใน ${module.title} หรือไม่?` })} className="inline-flex items-center gap-1 rounded-lg bg-amber-50 px-2.5 py-1.5 text-xs font-black text-amber-800 ring-1 ring-amber-100">
          <Icon name="archive" className="h-3.5 w-3.5" />ปิดการใช้งาน
        </button>
      )}
      {canCrud(role, "delete", moduleId) && !forceInactiveOnly && (
        <button onClick={() => setConfirm({ action: "delete", message: `ต้องการลบ "${itemName}" หรือไม่? ข้อมูลสำคัญควรใช้ Inactive เพื่อเก็บประวัติย้อนหลัง` })} className="inline-flex items-center gap-1 rounded-lg bg-red-50 px-2.5 py-1.5 text-xs font-black text-red-700 ring-1 ring-red-100">
          <Icon name="trash" className="h-3.5 w-3.5" />ลบ
        </button>
      )}
      {forceInactiveOnly && canCrud(role, "inactive", moduleId) && (
        <span className="inline-flex items-center rounded-lg bg-goodseed-50 px-2.5 py-1.5 text-xs font-black text-goodseed-700 ring-1 ring-goodseed-100">Finance ใช้ Inactive เท่านั้น</span>
      )}
      <CrudConfirmDialog
        confirm={confirm}
        onCancel={() => setConfirm(null)}
        onConfirm={() => {
          runAction(confirm.action, confirm.action === "delete" ? "ลบ" : "ปิดการใช้งาน");
          setConfirm(null);
        }}
      />
    </div>
  );
}

function CrudGovernanceBar({ role, moduleId, title }) {
  const module = crudModuleById(moduleId);
  const [query, setQuery] = useState("");
  const [status, setStatus] = useState("ทั้งหมด");
  const [modal, setModal] = useState(null);
  const [toast, setToast] = useState("");
  const [logs, setLogs] = useState([
    createAuditLog({ role, moduleId, action: "System Ready", itemName: module.sample[0], oldValue: "-", newValue: "Active", reason: "ติดตั้งมาตรฐาน CRUD กลาง" }),
  ]);
  const addLog = (log) => {
    setLogs((current) => [log, ...current].slice(0, 6));
    setToast(`${log.action} "${log.itemName}" สำเร็จ`);
  };
  const visibleSamples = module.sample.filter((item) => item.toLowerCase().includes(query.toLowerCase()));
  return (
    <div className="mb-5 rounded-2xl border border-goodseed-100 bg-white p-4 shadow-soft">
      <CrudToast message={toast} onClose={() => setToast("")} />
      <CrudModalForm
        open={Boolean(modal)}
        module={module}
        mode={modal?.mode}
        itemName={modal?.itemName}
        onClose={() => setModal(null)}
        onSave={(form) => {
          addLog(createAuditLog({
            role,
            moduleId,
            action: modal?.mode === "edit" ? "แก้ไข" : "เพิ่ม",
            itemName: form.name || form.custom || "รายการใหม่",
            oldValue: modal?.mode === "edit" ? modal?.itemName : "-",
            newValue: `${form.status} / ${form.category === "อื่น ๆ / ระบุเอง" ? form.custom : form.category}`,
            reason: form.reason,
          }));
          setModal(null);
        }}
      />
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div className="flex items-start gap-3">
          <div className="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-goodseed-100 text-goodseed-800"><Icon name={module.icon} /></div>
          <div>
            <div className="flex flex-wrap items-center gap-2">
              <h3 className="text-lg font-black text-goodseed-950">{title || module.title}</h3>
              <Badge className="bg-white text-goodseed-800 ring-goodseed-100">CRUD Standard</Badge>
              <Badge className={roleInfo(role).badge}>{roleInfo(role).label}</Badge>
            </div>
            <p className="mt-2 max-w-4xl text-sm font-semibold leading-6 text-goodseed-700">{crudGrowthMessage}</p>
            <p className="mt-1 text-xs font-bold text-goodseed-500">Policy: {module.policy}</p>
            {moduleId === "finance" && <p className="mt-2 rounded-lg bg-amber-50 px-3 py-2 text-xs font-black text-amber-800">รายการการเงิน เช่น รายรับไม้ล้อม จะไม่ถูกลบถาวรจากหน้านี้ ให้ใช้ Inactive เพื่อเก็บประวัติและ Audit Log</p>}
          </div>
        </div>
        <div className="flex flex-wrap gap-2">
          {canCrud(role, "add", moduleId) ? (
            <button onClick={() => setModal({ mode: "add" })} className="inline-flex items-center gap-2 rounded-xl bg-goodseed-700 px-4 py-2.5 text-sm font-black text-white shadow-sm hover:bg-goodseed-800">
              <Icon name="plus" className="h-4 w-4" />+ เพิ่มรายการใหม่
            </button>
          ) : (
            <Badge className="bg-slate-100 text-slate-600 ring-slate-200">Role นี้เพิ่มข้อมูลไม่ได้</Badge>
          )}
          <button onClick={() => setToast("Export Audit Log พร้อมใช้งาน")} className="inline-flex items-center gap-2 rounded-xl border border-goodseed-100 bg-white px-4 py-2.5 text-sm font-black text-goodseed-800">
            <Icon name="download" className="h-4 w-4" />Export Log
          </button>
        </div>
      </div>
      <div className="mt-4 grid gap-3 md:grid-cols-[1fr_220px]">
        <label className="relative">
          <span className="absolute left-3 top-1/2 -translate-y-1/2 text-goodseed-400"><Icon name="history" className="h-4 w-4" /></span>
          <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search / ค้นหารายการ..." className="w-full rounded-xl border border-goodseed-100 bg-goodseed-50 py-3 pl-10 pr-4 text-sm font-bold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" />
        </label>
        <select value={status} onChange={(event) => setStatus(event.target.value)} className="rounded-xl border border-goodseed-100 bg-white px-3 py-3 text-sm font-bold text-goodseed-800 outline-none">
          {["ทั้งหมด", ...crudStatusOptions].map((item) => <option key={item}>{item}</option>)}
        </select>
      </div>
      <div className="mt-4 grid gap-3 lg:grid-cols-3">
        {visibleSamples.map((item, index) => (
          <div key={item} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-3">
            <div className="flex items-start justify-between gap-3">
              <div>
                <p className="font-black text-goodseed-950">{item}</p>
                <p className="mt-1 text-xs font-bold text-goodseed-600">{module.fields[index % module.fields.length]} / {status === "ทั้งหมด" ? "Active" : status}</p>
              </div>
              <Badge className="bg-white text-goodseed-800 ring-goodseed-100">#{index + 1}</Badge>
            </div>
            <div className="mt-3">
              <CrudActionMenu
                role={role}
                moduleId={moduleId}
                itemName={item}
                onLog={addLog}
                onEdit={() => setModal({ mode: "edit", itemName: item })}
              />
            </div>
          </div>
        ))}
      </div>
      <details className="mt-4 rounded-xl border border-goodseed-100 bg-white p-3">
        <summary className="cursor-pointer text-sm font-black text-goodseed-900">Audit Log ล่าสุด</summary>
        <div className="mt-3 space-y-2">
          {logs.map((log) => (
            <div key={log.id} className="grid gap-2 rounded-lg bg-goodseed-50 p-3 text-xs font-bold text-goodseed-700 md:grid-cols-[130px_1fr_1fr_1fr]">
              <span>{log.time}</span>
              <span>{log.actor} / {log.action}</span>
              <span>{log.itemName}</span>
              <span>{log.oldValue} → {log.newValue}</span>
            </div>
          ))}
        </div>
      </details>
    </div>
  );
}

function CrudSystemManager({ role }) {
  const [logs, setLogs] = useState([]);
  const addLog = (log) => setLogs((current) => [log, ...current].slice(0, 8));
  return (
    <div className="mt-6 rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4 shadow-inner">
      <SectionHeader
        title="Global CRUD Governance"
        subtitle="มาตรฐานเพิ่ม / แก้ไข / ลบ / ปิดการใช้งาน / Audit Log สำหรับทุก Module สำคัญ"
        action={<Badge className={roleInfo(role).badge}>{roleInfo(role).label}</Badge>}
      />
      <div className="rounded-xl bg-white p-4 text-sm font-semibold leading-6 text-goodseed-800 ring-1 ring-goodseed-100">{crudGrowthMessage}</div>
      <div className="mt-4 grid gap-4 lg:grid-cols-2">
        {crudModules.map((module) => (
          <article key={module.id} className="rounded-2xl border border-goodseed-100 bg-white p-4 shadow-sm">
            <div className="flex items-start gap-3">
              <div className="grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-goodseed-100 text-goodseed-800"><Icon name={module.icon} /></div>
              <div className="min-w-0 flex-1">
                <h3 className="font-black text-goodseed-950">{module.title}</h3>
                <p className="mt-1 text-xs font-bold text-goodseed-600">Route: #{module.route}</p>
                <p className="mt-2 text-sm font-semibold leading-6 text-goodseed-700">{module.policy}</p>
              </div>
              <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{module.id}</Badge>
            </div>
            <div className="mt-3 flex flex-wrap gap-2">
              {module.fields.slice(0, 6).map((field) => <Badge key={field} className="bg-goodseed-50 text-goodseed-800 ring-goodseed-100">{field}</Badge>)}
              <Badge className="bg-amber-50 text-amber-800 ring-amber-100">อื่น ๆ / ระบุเอง</Badge>
            </div>
            <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
              <div className="flex flex-wrap gap-2">
                {canCrud(role, "add", module.id) && (
                  <button
                    onClick={() => addLog(createAuditLog({ role, moduleId: module.id, action: "เพิ่ม", itemName: `${module.sample[0]} ใหม่`, oldValue: "-", newValue: "Active", reason: "เพิ่มรายการใหม่จาก Global CRUD Governance" }))}
                    className="inline-flex items-center gap-2 rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-black text-white"
                  >
                    <Icon name="plus" className="h-3.5 w-3.5" />+ เพิ่มรายการใหม่
                  </button>
                )}
                <CrudActionMenu role={role} moduleId={module.id} itemName={module.sample[0]} onLog={addLog} />
              </div>
              <a href={`#${module.route}`} className="inline-flex items-center gap-2 rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-black text-white">ไปหน้า Module</a>
            </div>
          </article>
        ))}
      </div>
      <DashboardPanel title="Global Audit Log" className="mt-4">
        {logs.length ? logs.map((log) => (
          <div key={log.id} className="mb-2 rounded-lg bg-white p-3 text-sm font-bold text-goodseed-800 ring-1 ring-goodseed-100">
            {log.time} · {log.actor} · {log.module} · {log.action} · {log.itemName}
          </div>
        )) : <p className="text-sm font-semibold text-goodseed-600">ยังไม่มีรายการใหม่ในรอบนี้</p>}
      </DashboardPanel>
    </div>
  );
}

function ResponsibilityTable({ tasks, viewMode, role }) {
  const [tab, setTab] = useState("ผู้จัดการแปลง");
  const rows = tasks.filter((task) => task.role === tab);
  return (
    <section id="responsibility" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
      <SectionHeader title="ตารางงานและความรับผิดชอบ" subtitle="แยกเป็น Tab ผู้จัดการแปลงและคนงานฟาร์ม" action={["owner", "admin", "manager"].includes(role) ? <ExportButtons tasks={tasks} /> : <Badge className={roleInfo(role).badge}>{roleInfo(role).label}</Badge>} />
      <CrudGovernanceBar role={role} moduleId="work-plan" title="Work Plan / Calendar CRUD" />
      <div className="mb-4 flex rounded-lg bg-goodseed-50 p-1">
        {["ผู้จัดการแปลง", "คนงานฟาร์ม"].map((role) => <button key={role} onClick={() => setTab(role)} className={`flex-1 rounded-md px-3 py-2 text-sm font-extrabold transition ${tab === role ? "bg-white text-goodseed-900 shadow-sm" : "text-goodseed-700"}`}>{role}</button>)}
      </div>
      <TaskTable rows={rows} viewMode={viewMode} />
      <DailyResponsibilityEditor />
      <EditableYearCalendar viewMode={viewMode} role={role} />
    </section>
  );
}

function DailyResponsibilityEditor() {
  const [tableFormat, setTableFormat] = useState("ตารางงานรายวัน");
  const [rows, setRows] = useState(defaultDailyWorkRows);
  const [note, setNote] = useState({
    managerSummary: "สรุปผลการทำงานวันนี้ และรูปภาพที่ต้องส่งเจ้าของฟาร์ม",
    followUp: "ปัญหาที่พบ / งานที่ต้องติดตาม",
    workerDone: "งานที่เสร็จตามแผน",
    workerIssue: "งานที่ยังไม่เสร็จ / พบปัญหา",
  });
  const [signatures, setSignatures] = useState({ worker: "พี่ไกร / พี่สมชาย", inspector: "คุณหวาน" });

  const updateRow = (index, key, value) => {
    setRows((current) => current.map((row, rowIndex) => (rowIndex === index ? { ...row, [key]: value } : row)));
  };
  const updateNote = (key, value) => setNote((current) => ({ ...current, [key]: value }));
  const updateSignature = (key, value) => setSignatures((current) => ({ ...current, [key]: value }));
  const responsibilityRows = buildResponsibilityRows(rows, tableFormat);

  const downloadResponsibilityCsv = () => {
    const csvRows = [["วันที่", "ชื่อผู้รับผิดชอบ", "ตำแหน่ง", "ช่วงเวลา", "งานที่ได้รับมอบหมาย", "พื้นที่ / แปลงที่รับผิดชอบ", "สถานะงาน", "หมายเหตุ"], ...responsibilityRows.map((row) => [row.date, row.owner, row.role, row.time, row.task, row.area, row.status, row.note])];
    downloadFile("goodseed-responsibility-table.csv", "\ufeff" + csvRows.map((row) => row.map((cell) => `"${String(cell).replaceAll('"', '""')}"`).join(",")).join("\n"), "text/csv;charset=utf-8");
  };

  const downloadResponsibilityPng = () => {
    const canvas = document.createElement("canvas");
    canvas.width = 1400;
    canvas.height = 220 + responsibilityRows.length * 58;
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "#f8fbf7";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#173419";
    ctx.font = "bold 38px sans-serif";
    ctx.fillText("GoodSeed Farm - ตารางความรับผิดชอบ", 48, 64);
    ctx.font = "24px sans-serif";
    ctx.fillText(tableFormat, 48, 104);
    const columns = [48, 190, 390, 560, 730, 980, 1160];
    const heads = ["วันที่", "ผู้รับผิดชอบ", "ตำแหน่ง", "เวลา", "งาน", "พื้นที่", "สถานะ"];
    ctx.fillStyle = "#285b22";
    ctx.fillRect(40, 140, 1320, 46);
    ctx.fillStyle = "#ffffff";
    ctx.font = "bold 20px sans-serif";
    heads.forEach((head, index) => ctx.fillText(head, columns[index], 170));
    responsibilityRows.forEach((row, index) => {
      const y = 210 + index * 58;
      ctx.fillStyle = index % 2 ? "#ffffff" : "#eef7eb";
      ctx.fillRect(40, y - 30, 1320, 50);
      ctx.fillStyle = "#173419";
      ctx.font = "18px sans-serif";
      [row.date, row.owner, row.role, row.time, row.task, row.area, row.status].forEach((cell, cellIndex) => ctx.fillText(String(cell).slice(0, 24), columns[cellIndex], y));
    });
    const link = document.createElement("a");
    link.download = "goodseed-responsibility-table.png";
    link.href = canvas.toDataURL("image/png");
    link.click();
  };

  return (
    <div className="mt-6 rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
      <SectionHeader
        title="ตารางความรับผิดชอบรายวัน"
        subtitle="แสดงความรับผิดชอบของผู้จัดการแปลงและคนงาน พร้อมดาวน์โหลดไฟล์และสั่งพิมพ์"
        action={<div className="flex flex-wrap gap-2">
          <button onClick={() => window.print()} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-sm font-extrabold text-goodseed-800 shadow-sm"><Icon name="file" className="h-4 w-4" />สั่งพิมพ์</button>
          <button onClick={() => window.print()} className="inline-flex items-center gap-2 rounded-lg border border-red-200 bg-white px-3 py-2 text-sm font-extrabold text-red-700 shadow-sm"><Icon name="download" className="h-4 w-4" />PDF</button>
          <button onClick={downloadResponsibilityCsv} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-sm font-extrabold text-goodseed-800 shadow-sm"><Icon name="download" className="h-4 w-4" />Excel</button>
          <button onClick={downloadResponsibilityPng} className="inline-flex items-center gap-2 rounded-lg border border-blue-200 bg-white px-3 py-2 text-sm font-extrabold text-blue-700 shadow-sm"><Icon name="camera" className="h-4 w-4" />PNG</button>
        </div>}
      />
      <div className="mb-5 rounded-lg border border-goodseed-100 bg-white p-4 shadow-sm">
        <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
          <div>
            <h3 className="text-lg font-extrabold text-goodseed-950">ตารางรวมผู้จัดการแปลงและคนงาน</h3>
            <p className="mt-1 text-sm font-semibold text-goodseed-700">ไฟล์ดาวน์โหลดและหน้าพิมพ์ใช้ข้อมูลเดียวกับตารางนี้</p>
          </div>
          <div className="w-full max-w-xs">
            <Select label="รูปแบบตาราง" value={tableFormat} onChange={setTableFormat} options={["ตารางงานรายวัน", "ตารางงานรายสัปดาห์", "ตารางงานรายเดือน"]} />
          </div>
        </div>
        <ResponsibilityPrintTable rows={responsibilityRows} />
      </div>
      <div className="mb-5 grid gap-4 lg:grid-cols-2">
        {dailyResponsibilityImages.map((item) => (
          <a key={item.src} href={item.src} target="_blank" rel="noreferrer" className="overflow-hidden rounded-lg border border-goodseed-100 bg-white shadow-sm">
            <div className="grid max-h-[520px] place-items-center bg-white p-2">
              <img src={item.src} alt={item.title} className="max-h-[500px] w-full object-contain" />
            </div>
            <div className="border-t border-goodseed-100 p-3">
              <p className="font-extrabold text-goodseed-900">{item.title}</p>
              <p className="mt-1 text-sm text-goodseed-700">{item.detail}</p>
            </div>
          </a>
        ))}
      </div>
      <div className="thin-scrollbar overflow-x-auto rounded-lg border border-goodseed-100 bg-white">
        <table className="min-w-[1200px] w-full divide-y divide-goodseed-100 text-left text-sm">
          <thead className="bg-goodseed-700 text-white">
            <tr>
              {["เวลา", "งานผู้จัดการแปลง", "รายละเอียดผู้จัดการ", "งานคนงาน", "รายละเอียด / พื้นที่", "ผู้รับผิดชอบ", "เสร็จแล้ว", "หมายเหตุ"].map((head) => (
                <th key={head} className="px-3 py-3 font-extrabold">{head}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-goodseed-100">
            {rows.map((row, index) => (
              <tr key={row.time} className={row.time === "12.00 - 13.00" ? "bg-amber-50" : "bg-white"}>
                <td className="whitespace-nowrap px-3 py-3 font-extrabold text-goodseed-900">{row.time}</td>
                <td className="px-3 py-3"><EditableCell value={row.managerTask} onChange={(value) => updateRow(index, "managerTask", value)} /></td>
                <td className="px-3 py-3"><EditableCell value={row.managerDetail} onChange={(value) => updateRow(index, "managerDetail", value)} wide /></td>
                <td className="px-3 py-3"><EditableCell value={row.workerTask} onChange={(value) => updateRow(index, "workerTask", value)} /></td>
                <td className="px-3 py-3"><EditableCell value={row.workerDetail} onChange={(value) => updateRow(index, "workerDetail", value)} wide /></td>
                <td className="px-3 py-3"><EditableCell value={row.owner} onChange={(value) => updateRow(index, "owner", value)} /></td>
                <td className="px-3 py-3 text-center">
                  <input type="checkbox" checked={row.done} onChange={(event) => updateRow(index, "done", event.target.checked)} className="h-5 w-5 rounded border-goodseed-300 text-goodseed-700 focus:ring-goodseed-500" />
                </td>
                <td className="px-3 py-3"><EditableCell value={row.note} onChange={(value) => updateRow(index, "note", value)} placeholder="หมายเหตุ..." /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="mt-4 grid gap-4 md:grid-cols-2">
        <SummaryBox title="สรุปผลการทำงานวันนี้" value={note.managerSummary} onChange={(value) => updateNote("managerSummary", value)} tone="good" />
        <SummaryBox title="ปัญหาที่พบ / งานที่ต้องติดตาม" value={note.followUp} onChange={(value) => updateNote("followUp", value)} tone="warning" />
        <SummaryBox title="งานที่เสร็จตามแผน" value={note.workerDone} onChange={(value) => updateNote("workerDone", value)} tone="good" />
        <SummaryBox title="งานที่ยังไม่เสร็จ / พบปัญหา" value={note.workerIssue} onChange={(value) => updateNote("workerIssue", value)} tone="warning" />
      </div>
      <div className="mt-4 grid gap-4 md:grid-cols-2">
        <Input label="ลงชื่อผู้ปฏิบัติงาน" value={signatures.worker} onChange={(value) => updateSignature("worker", value)} />
        <Input label="ลงชื่อผู้ตรวจงาน" value={signatures.inspector} onChange={(value) => updateSignature("inspector", value)} />
      </div>
    </div>
  );
}

function buildResponsibilityRows(rows, tableFormat) {
  const date = tableFormat === "ตารางงานรายเดือน" ? "พฤษภาคม 2569" : tableFormat === "ตารางงานรายสัปดาห์" ? "20-26 พ.ค. 2569" : "25 พ.ค. 2569";
  return rows.flatMap((row) => {
    if (row.time === "12.00 - 13.00") {
      return [
        { date, owner: "ทีมฟาร์ม", role: "ผู้จัดการแปลง / คนงาน", time: row.time, task: "พักกลางวัน", area: "ศูนย์ปฏิบัติงาน", status: "ยังไม่เริ่ม", note: "พักและเตรียมงานรอบบ่าย" },
      ];
    }
    return [
      { date, owner: "คุณหวาน", role: "ผู้จัดการแปลง", time: row.time, task: row.managerTask, area: row.managerDetail, status: row.done ? "เสร็จแล้ว" : "กำลังดำเนินการ", note: row.note || "ตรวจและบันทึกผล" },
      { date, owner: row.owner, role: "คนงาน", time: row.time, task: row.workerTask, area: row.workerDetail, status: row.done ? "เสร็จแล้ว" : "ยังไม่เริ่ม", note: row.note || "รออัปเดตรูปหลักฐาน" },
    ];
  });
}

function ResponsibilityPrintTable({ rows }) {
  return (
    <div className="thin-scrollbar overflow-x-auto rounded-lg border border-goodseed-100">
      <table className="min-w-[980px] w-full text-left text-sm">
        <thead className="bg-goodseed-700 text-white">
          <tr>
            {["วันที่", "ชื่อผู้รับผิดชอบ", "ตำแหน่ง", "ช่วงเวลา", "งานที่ได้รับมอบหมาย", "พื้นที่ / แปลงที่รับผิดชอบ", "สถานะงาน", "หมายเหตุ"].map((head) => (
              <th key={head} className="px-3 py-3 font-extrabold">{head}</th>
            ))}
          </tr>
        </thead>
        <tbody className="divide-y divide-goodseed-100 bg-white">
          {rows.map((row, index) => (
            <tr key={`${row.date}-${row.role}-${row.time}-${index}`} className={row.role.includes("ผู้จัดการ") ? "bg-goodseed-50/60" : "bg-white"}>
              <td className="whitespace-nowrap px-3 py-3 font-bold text-goodseed-900">{row.date}</td>
              <td className="px-3 py-3 font-extrabold text-goodseed-950">{row.owner}</td>
              <td className="px-3 py-3">{row.role}</td>
              <td className="whitespace-nowrap px-3 py-3">{row.time}</td>
              <td className="px-3 py-3 font-semibold text-goodseed-900">{row.task}</td>
              <td className="px-3 py-3 text-goodseed-700">{row.area}</td>
              <td className="px-3 py-3"><StatusBadge status={row.status} /></td>
              <td className="px-3 py-3 text-goodseed-700">{row.note}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function EditableCell({ value, onChange, placeholder = "กรอกข้อมูล...", wide }) {
  return (
    <textarea
      value={value}
      onChange={(event) => onChange(event.target.value)}
      placeholder={placeholder}
      rows={wide ? 3 : 2}
      className="w-full min-w-40 resize-none rounded-md border border-goodseed-100 bg-goodseed-50/50 px-2 py-2 text-xs font-semibold text-goodseed-900 outline-none focus:border-goodseed-300 focus:bg-white focus:ring-2 focus:ring-goodseed-200"
    />
  );
}

function SummaryBox({ title, value, onChange, tone }) {
  const color = tone === "warning" ? "border-orange-200 bg-orange-50 text-orange-800" : "border-goodseed-200 bg-goodseed-50 text-goodseed-900";
  return (
    <label className={`rounded-lg border p-4 ${color}`}>
      <span className="font-extrabold">{title}</span>
      <textarea value={value} onChange={(event) => onChange(event.target.value)} rows="4" className="mt-3 w-full resize-none rounded-md border border-white/80 bg-white px-3 py-2 text-sm text-goodseed-900 outline-none focus:ring-2 focus:ring-goodseed-200" />
    </label>
  );
}

function EditableYearCalendar({ viewMode, role = "owner" }) {
  const [activeMonth, setActiveMonth] = useState(4);
  const [calendar, setCalendar] = useState(() => {
    const raw = buildInitialCalendar();
    return Object.fromEntries(Object.entries(raw).map(([month, days]) => [
      month,
      Object.fromEntries(Object.entries(days).map(([day, value]) => [day, [{
        type: value.includes("วันหยุด") ? "วันหยุด" : value.includes("เข้าตรวจงาน") ? "วันตรวจงาน" : value.includes("ประชุม") ? "วันประชุม" : "งานทั่วไป",
        title: value.split("\n")[0] || "งานฟาร์ม",
        detail: value,
        owner: "คุณหวาน",
        status: value.includes("วันหยุด") ? "ยังไม่เริ่ม" : "กำลังดำเนินการ",
        start: "08:00",
        end: "17:00",
        link: "",
        note: "",
      }]])),
    ]));
  });
  const [editing, setEditing] = useState(null);
  const days = getCalendarDays(calendarYear, activeMonth);
  const monthTasks = calendar[activeMonth] || {};

  const openDay = (day, type = "งานทั่วไป") => {
    if (!day) return;
    const existing = (monthTasks[day] || [])[0];
    setEditing(existing ? { day, ...existing } : { day, type, title: "", detail: "", owner: "คุณหวาน", status: "ยังไม่เริ่ม", start: "08:00", end: "17:00", link: "", note: "" });
  };

  const saveEvent = () => {
    setCalendar((current) => ({
      ...current,
      [activeMonth]: {
        ...(current[activeMonth] || {}),
        [editing.day]: [{ type: editing.type, title: editing.title || editing.type, detail: editing.detail, owner: editing.owner, status: editing.status, start: editing.start, end: editing.end, link: editing.link, note: editing.note }],
      },
    }));
    setEditing(null);
  };

  const deleteEvent = () => {
    setCalendar((current) => {
      const nextMonth = { ...(current[activeMonth] || {}) };
      delete nextMonth[editing.day];
      return { ...current, [activeMonth]: nextMonth };
    });
    setEditing(null);
  };

  const quickAdd = (type) => {
    const firstEmpty = Array.from({ length: new Date(calendarYear, activeMonth + 1, 0).getDate() }, (_, index) => index + 1).find((day) => !(monthTasks[day] || []).length) || 1;
    openDay(firstEmpty, type);
  };

  return (
    <div className="mt-6 rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
      <SectionHeader
        title={`ปฏิทินงานรายเดือน ${thaiYear}`}
        subtitle="กดช่องวันที่เพื่อเพิ่ม แก้ไข ลบ และบันทึกรายละเอียดงาน พร้อมแสดง Badge ในปฏิทินทันที"
        action={<Badge className="bg-white text-goodseed-800 ring-goodseed-200">บันทึกในหน้า Mock</Badge>}
      />
      <div className="grid gap-5 xl:grid-cols-[0.76fr_1.24fr]">
        <div className="space-y-4">
          <a href={monthlyScheduleExample} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-lg border border-goodseed-100 bg-white">
            <div className="grid min-h-48 place-items-center bg-white p-2">
              <img src={monthlyScheduleExample} alt="ตัวอย่างตารางงานรายเดือน" className="max-h-80 w-full object-contain" />
            </div>
            <div className="border-t border-goodseed-100 p-3">
              <p className="font-extrabold text-goodseed-900">ตัวอย่างตารางงานรายเดือน</p>
              <p className="mt-1 text-sm text-goodseed-700">คลิกเพื่อเปิดดูภาพเต็ม</p>
            </div>
          </a>
          <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 xl:grid-cols-2">
            {monthNames.map((month, index) => (
              <button
                key={month}
                onClick={() => setActiveMonth(index)}
                className={`rounded-lg px-3 py-2 text-sm font-extrabold transition ${
                  activeMonth === index ? "bg-goodseed-700 text-white shadow-sm" : "bg-white text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-100"
                }`}
              >
                {month}
              </button>
            ))}
          </div>
        </div>
        <div className="overflow-hidden rounded-lg border border-goodseed-100 bg-white">
          <div className="flex flex-col gap-2 border-b border-goodseed-100 bg-white p-4 sm:flex-row sm:items-end sm:justify-between">
            <div>
              <h3 className="text-2xl font-extrabold text-goodseed-900">{monthNames[activeMonth]} {thaiYear}</h3>
              <p className="mt-1 text-sm text-goodseed-700">กดวันที่หรือ Badge เพื่อเปิดรายละเอียดงาน</p>
            </div>
            <div className="flex flex-wrap gap-2">
              {activityTypes.slice(0, 5).map((type) => <button key={type} onClick={() => quickAdd(type)} className={`rounded-full px-3 py-1 text-xs font-extrabold ring-1 ${activityClasses[type]}`}>เพิ่ม{type}</button>)}
            </div>
          </div>
          {viewMode === "mobile" ? (
            <div className="space-y-3 p-3">
              {Array.from({ length: new Date(calendarYear, activeMonth + 1, 0).getDate() }, (_, index) => index + 1).map((day) => (
                <button key={day} onClick={() => openDay(day)} className="w-full rounded-lg border border-goodseed-100 bg-white p-3 text-left shadow-sm">
                  <div className="flex items-start justify-between gap-3"><span className="text-xl font-extrabold text-goodseed-900">{day}</span><span className="text-xs font-bold text-goodseed-600">{monthNames[activeMonth]}</span></div>
                  <CalendarEventBadges events={monthTasks[day] || []} />
                </button>
              ))}
            </div>
          ) : <div className="thin-scrollbar overflow-x-auto">
            <div className="min-w-[980px]">
              <div className="grid grid-cols-7 border-b border-goodseed-100 bg-goodseed-100/70">
                {weekDays.map((day) => <div key={day} className="border-r border-goodseed-200 px-3 py-2 text-center text-sm font-extrabold text-goodseed-900 last:border-r-0">{day}</div>)}
              </div>
              <div className="grid grid-cols-7">
                {days.map((day, index) => (
                  <CalendarDayCell
                    key={`${activeMonth}-${index}`}
                    day={day}
                    events={day ? monthTasks[day] || [] : []}
                    onOpen={() => openDay(day)}
                  />
                ))}
              </div>
            </div>
          </div>}
        </div>
      </div>
      {editing && (
        <div className="fixed inset-0 z-[80] grid place-items-center bg-goodseed-950/45 p-4">
          <div className="max-h-[92vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-5 shadow-2xl">
            <div className="mb-4 flex items-start justify-between gap-3">
              <div><h3 className="text-xl font-extrabold text-goodseed-950">รายละเอียดวันที่ {editing.day} {monthNames[activeMonth]} {thaiYear}</h3><p className="text-sm font-semibold text-goodseed-700">เพิ่ม แก้ไข หรือลบกิจกรรมของวันนั้น</p></div>
              <button onClick={() => setEditing(null)} className="rounded-lg border border-goodseed-100 p-2 text-goodseed-800"><Icon name="x" /></button>
            </div>
            <div className="grid gap-4 md:grid-cols-2">
              <Input label="วันที่" value={`${editing.day} ${monthNames[activeMonth]} ${thaiYear}`} onChange={() => {}} />
              <Select label="ประเภทกิจกรรม" value={editing.type} onChange={(value) => setEditing((current) => ({ ...current, type: value }))} options={activityTypes} />
              <Input label="หัวข้องาน" value={editing.title} onChange={(value) => setEditing((current) => ({ ...current, title: value }))} />
              <Select label="สถานะงาน" value={editing.status} onChange={(value) => setEditing((current) => ({ ...current, status: value }))} options={["ยังไม่เริ่ม", "กำลังดำเนินการ", "เสร็จแล้ว", "เลื่อนออกไป", "ยกเลิก"]} />
              <Textarea label="รายละเอียดงาน" value={editing.detail} onChange={(value) => setEditing((current) => ({ ...current, detail: value }))} wide />
              <Input label="ผู้รับผิดชอบ" value={editing.owner} onChange={(value) => setEditing((current) => ({ ...current, owner: value }))} />
              <Input label="เวลาเริ่มต้น" value={editing.start} onChange={(value) => setEditing((current) => ({ ...current, start: value }))} />
              <Input label="เวลาสิ้นสุด" value={editing.end} onChange={(value) => setEditing((current) => ({ ...current, end: value }))} />
              <Input label="แนบลิงก์ Google Form / หลักฐาน / รูปภาพ" value={editing.link} onChange={(value) => setEditing((current) => ({ ...current, link: value }))} />
              <Input label="หมายเหตุ" value={editing.note} onChange={(value) => setEditing((current) => ({ ...current, note: value }))} />
            </div>
            <div className="mt-5 flex flex-wrap justify-end gap-2">
              {isOwnerRole(role) && <button onClick={deleteEvent} className="rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm font-extrabold text-red-700">ลบ</button>}
              <button onClick={() => setEditing(null)} className="rounded-lg border border-goodseed-100 px-4 py-2 text-sm font-extrabold text-goodseed-800">ปิด</button>
              <button onClick={saveEvent} className="rounded-lg bg-goodseed-700 px-5 py-2 text-sm font-extrabold text-white">บันทึก</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function CalendarEventBadges({ events }) {
  if (!events.length) return <p className="mt-2 text-xs font-semibold text-slate-400">กดเพื่อเพิ่มรายละเอียดงาน</p>;
  return <div className="mt-2 space-y-1">{events.slice(0, 2).map((event, index) => <div key={`${event.title}-${index}`} className="space-y-1"><Badge className={activityClasses[event.type] || activityClasses["งานทั่วไป"]}>{event.type}</Badge><p className="truncate text-xs font-extrabold text-goodseed-900">{event.title}</p><StatusBadge status={event.status} /></div>)}{events.length > 2 && <p className="text-xs font-extrabold text-goodseed-700">+ เพิ่มเติม</p>}</div>;
}

function CalendarDayCell({ day, events, onOpen }) {
  return (
    <button onClick={onOpen} className={`min-h-44 border-b border-r border-goodseed-100 p-2 text-left transition hover:bg-goodseed-50 ${events.some((event) => event.type === "วันหยุด") ? "bg-red-50" : "bg-white"}`}>
      {day ? (
        <>
          <div className="mb-2 flex items-center justify-between gap-2">
            <span className={`text-2xl font-extrabold ${events.some((event) => event.type === "วันหยุด") ? "text-red-600" : "text-goodseed-900"}`}>{day}</span>
          </div>
          <CalendarEventBadges events={events} />
        </>
      ) : (
        <div className="h-full rounded-md bg-slate-50" />
      )}
    </button>
  );
}

function TaskTable({ rows, viewMode }) {
  const heads = ["ลำดับ", "ชื่อผู้รับผิดชอบ", "หน้าที่ / งานที่ต้องทำ", "พื้นที่ / แปลง", "ความถี่", "สถานะ", "รูปภาพหลักฐาน", "หมายเหตุ"];
  if (viewMode === "mobile") {
    return (
      <div className="space-y-3">
        {rows.map((task) => (
          <div key={task.id} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <div>
                <p className="text-xs font-extrabold text-goodseed-600">ลำดับ {task.id}</p>
                <h3 className="mt-1 font-extrabold text-goodseed-950">{task.owner}</h3>
              </div>
              <StatusBadge status={task.status} />
            </div>
            <p className="mt-3 text-sm font-bold text-goodseed-900">{task.duty}</p>
            <div className="mt-3 grid gap-2 text-xs font-bold text-goodseed-700">
              <span className="rounded-md bg-goodseed-50 p-2">พื้นที่ / แปลง: {task.area}</span>
              <span className="rounded-md bg-goodseed-50 p-2">ความถี่: {task.frequency}</span>
              <span className="rounded-md bg-goodseed-50 p-2">รูปภาพหลักฐาน: {task.image}</span>
              <span className="rounded-md bg-goodseed-50 p-2">หมายเหตุ: {task.note}</span>
            </div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="thin-scrollbar overflow-x-auto rounded-lg border border-goodseed-100">
      <table className="min-w-[980px] w-full divide-y divide-goodseed-100 text-left text-sm">
        <thead className="bg-goodseed-50 text-goodseed-800"><tr>{heads.map((head) => <th key={head} className="px-4 py-3 font-extrabold">{head}</th>)}</tr></thead>
        <tbody className="divide-y divide-goodseed-100 bg-white">
          {rows.map((task) => <tr key={task.id} className="align-top"><td className="px-4 py-3 font-bold">{task.id}</td><td className="px-4 py-3">{task.owner}</td><td className="px-4 py-3 font-semibold text-goodseed-900">{task.duty}</td><td className="px-4 py-3">{task.area}</td><td className="px-4 py-3">{task.frequency}</td><td className="px-4 py-3"><StatusBadge status={task.status} /></td><td className="px-4 py-3"><span className="inline-flex items-center gap-2"><Icon name="camera" className="h-4 w-4" />{task.image}</span></td><td className="px-4 py-3 text-goodseed-700">{task.note}</td></tr>)}
        </tbody>
      </table>
    </div>
  );
}

function SchedulePages({ role = "owner" }) {
  return (
    <section id="daily-work" className="grid gap-5 xl:grid-cols-3">
      <div className="xl:col-span-3">
        <CrudGovernanceBar role={role} moduleId="work-plan" title="Work Plan / Calendar CRUD" />
      </div>
      <SchedulePanel title="ปฏิทินการทำงานประจำเดือน" rows={scheduleMonth.map(([date, work, status]) => [`วันที่ ${date}`, work, status])} />
      <SchedulePanel title="ตารางงานรายสัปดาห์" rows={weeklyRows.map(([day, work, owner]) => [day, work, owner])} />
      <SchedulePanel title="ตารางงานรายวัน" rows={dailyRows.map(([time, work, owner, status]) => [time, `${work} - ${owner}`, status])} />
    </section>
  );
}

function SchedulePanel({ title, rows }) {
  return <div className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft"><h3 className="font-extrabold text-goodseed-900">{title}</h3><div className="mt-4 space-y-3">{rows.map(([a, b, c]) => <div key={`${a}${b}`} className="rounded-lg bg-goodseed-50 p-3"><div className="flex items-start justify-between gap-3"><p className="font-bold text-goodseed-900">{a}</p>{statusClasses[c] ? <StatusBadge status={c} /> : <Badge className="bg-white text-goodseed-700 ring-goodseed-100">{c}</Badge>}</div><p className="mt-2 text-sm text-goodseed-700">{b}</p></div>)}</div></div>;
}

function QRCard({ item, active, onClick }) {
  return (
    <button onClick={onClick} className={`flex items-center gap-3 rounded-lg border p-4 text-left transition ${active ? "border-goodseed-600 bg-goodseed-50" : "border-goodseed-100 bg-white hover:bg-goodseed-50"}`}>
      <div className="grid h-11 w-11 shrink-0 place-items-center rounded-lg bg-goodseed-700 text-white"><Icon name={item.icon} /></div>
      <div className="min-w-0"><p className="font-extrabold text-goodseed-900">{item.title}</p><p className="truncate text-sm text-goodseed-700">{item.latest}</p></div>
    </button>
  );
}

function QRManagement() {
  const [active, setActive] = useState(qrItems[0]);
  return (
    <section id="trees" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
      <SectionHeader title="QR Management" subtitle="กดดู QR เพื่อแสดงข้อมูลล่าสุดและประวัติย้อนหลังของรายการนั้น" />
      <div className="grid gap-5 lg:grid-cols-[0.9fr_1.1fr]">
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">{qrItems.map((item) => <QRCard key={item.code} item={item} active={active.code === item.code} onClick={() => setActive(item)} />)}</div>
        <div className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-5">
          <div className="flex flex-col gap-5 md:flex-row">
            <QrMock code={active.code} />
            <div><Badge className="bg-goodseed-700 text-white ring-goodseed-700">ข้อมูลล่าสุด</Badge><h3 className="mt-3 text-2xl font-extrabold text-goodseed-900">{active.title}</h3><p className="mt-1 font-mono text-sm text-goodseed-700">{active.code}</p><p className="mt-4 text-goodseed-800">{active.latest}</p><div className="mt-4 grid gap-3 sm:grid-cols-2"><MiniMetric label="ประวัติย้อนหลัง" value={`${active.history.length} รายการ`} /><MiniMetric label="ภาพแนบล่าสุด" value="8 ภาพ" /></div></div>
          </div>
          <div className="mt-5 rounded-lg bg-white p-4"><p className="font-bold text-goodseed-900">ประวัติย้อนหลัง</p><ol className="mt-3 space-y-3 text-sm text-goodseed-800">{active.history.map((item) => <li key={item} className="border-l-2 border-goodseed-300 pl-3">{item}</li>)}</ol></div>
        </div>
      </div>
    </section>
  );
}

function QrMock({ code }) {
  const cells = useMemo(() => Array.from({ length: 49 }, (_, index) => (code.charCodeAt(index % code.length) + index * 7) % 3 !== 0), [code]);
  return <div className="grid h-52 w-52 shrink-0 grid-cols-7 gap-1 rounded-lg bg-white p-4 shadow-soft">{cells.map((on, index) => <span key={index} className={`rounded-sm ${on ? "bg-goodseed-900" : "bg-goodseed-50"}`} />)}</div>;
}

function OwnerReview({ reports, tasks }) {
  return (
    <section id="owner-review" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
      <SectionHeader title="Owner Review" subtitle="เจ้าของฟาร์มตรวจรายงาน รูปถ่าย งานค้าง ปัญหาที่ต้องอนุมัติ และประวัติย้อนหลัง" action={<ExportButtons tasks={tasks} reports={reports} />} />
      <div className="grid gap-4 lg:grid-cols-4">
        <MiniMetric label="รายงานรายวัน" value={`${reports.length} ฉบับ`} />
        <MiniMetric label="งานที่เสร็จ" value={`${tasks.filter((t) => t.status === "เสร็จแล้ว").length} งาน`} />
        <MiniMetric label="งานค้าง" value={`${tasks.filter((t) => t.status !== "เสร็จแล้ว").length} งาน`} danger />
        <MiniMetric label="ปัญหาต้องอนุมัติ" value="2 รายการ" danger />
      </div>
      <div className="mt-5 grid gap-5 xl:grid-cols-[1.2fr_0.8fr]">
        <div className="space-y-3">{reports.map((report) => <div key={report.id} className="rounded-lg border border-goodseed-100 p-4"><div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between"><div><p className="font-extrabold text-goodseed-900">{report.date} | {report.area}</p><p className="text-sm text-goodseed-700">ผู้รายงาน: {report.reporter} | {report.weather}</p></div><Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{report.photos}</Badge></div><p className="mt-3 text-sm text-goodseed-800">{report.summary}</p><p className="mt-2 text-xs font-bold text-goodseed-600">รูปถ่ายจากแปลง: {report.photos} | รูปสรุป: {report.summaryPhoto}</p></div>)}</div>
        <div className="rounded-lg bg-goodseed-50 p-4"><p className="font-extrabold text-goodseed-900">ประวัติย้อนหลังและรายการอนุมัติ</p><div className="mt-4 space-y-3">{["อนุมัติเลื่อนใส่ปุ๋ยแปลง B1", "ตรวจรับวัสดุคลุมดินรอบใหม่", "อนุมัติซ่อมปั๊มน้ำ EQ-PUMP-07"].map((item, index) => <div key={item} className="rounded-lg bg-white p-3"><div className="flex items-center justify-between gap-3"><p className="text-sm font-bold text-goodseed-900">{item}</p><Badge className={index === 0 ? "bg-red-100 text-red-700 ring-red-200" : "bg-amber-100 text-amber-800 ring-amber-200"}>{index === 0 ? "รออนุมัติ" : "ติดตาม"}</Badge></div></div>)}</div></div>
      </div>
    </section>
  );
}

function ExportButtons({ tasks = initialTasks, reports = initialReports }) {
  const exportExcel = () => {
    const rows = [["ลำดับ", "ชื่อผู้รับผิดชอบ", "หน้าที่ / งานที่ต้องทำ", "พื้นที่ / แปลง", "ความถี่", "สถานะ", "รูปภาพหลักฐาน", "หมายเหตุ"], ...tasks.map((task) => [task.id, task.owner, task.duty, task.area, task.frequency, task.status, task.image, task.note])];
    downloadFile("goodseed-export.csv", "\ufeff" + rows.map((row) => row.map((cell) => `"${String(cell).replaceAll('"', '""')}"`).join(",")).join("\n"), "text/csv;charset=utf-8");
  };
  const exportWord = () => downloadFile("goodseed-owner-review.doc", `<html><meta charset="utf-8"><body><h1>GoodSeed Owner Review</h1>${reports.map((r) => `<h2>${r.date} ${r.area}</h2><p>${r.summary}</p>`).join("")}</body></html>`, "application/msword;charset=utf-8");
  const exportImage = () => {
    const canvas = document.createElement("canvas");
    canvas.width = 1200; canvas.height = 680;
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "#f8fbf7"; ctx.fillRect(0, 0, 1200, 680);
    ctx.fillStyle = "#173419"; ctx.font = "bold 42px sans-serif"; ctx.fillText("GoodSeed Farm Management System", 60, 86);
    ctx.font = "24px sans-serif"; ctx.fillText(`รายงานล่าสุด ${reports[0].area}: ${reports[0].summary}`, 60, 135);
    [["แปลงทั้งหมด", "18"], ["ต้นไม้ทั้งหมด", "12,480"], ["รายงาน", reports.length], ["งานค้าง", tasks.filter((t) => t.status !== "เสร็จแล้ว").length]].forEach(([label, value], i) => {
      const x = 60 + i * 275; ctx.fillStyle = i === 0 ? "#285b22" : "#ffffff"; ctx.strokeStyle = "#b9dfb1"; ctx.beginPath(); ctx.roundRect(x, 190, 240, 140, 16); ctx.fill(); ctx.stroke(); ctx.fillStyle = i === 0 ? "#ffffff" : "#173419"; ctx.font = "22px sans-serif"; ctx.fillText(label, x + 22, 245); ctx.font = "bold 34px sans-serif"; ctx.fillText(String(value), x + 22, 295);
    });
    const link = document.createElement("a"); link.download = "goodseed-dashboard.png"; link.href = canvas.toDataURL("image/png"); link.click();
  };
  return <div className="no-print flex flex-wrap gap-2">{[["Download รูปภาพ", exportImage], ["Export Excel", exportExcel], ["Export Word", exportWord], ["Export PDF", () => window.print()]].map(([label, action]) => <button key={label} onClick={action} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-sm font-bold text-goodseed-800 shadow-sm transition hover:bg-goodseed-50"><Icon name="download" className="h-4 w-4" />{label}</button>)}</div>;
}

const assetCategoryOptions = [
  "รถยนต์ / รถกระบะ",
  "รถไถ / รถแทรกเตอร์",
  "เครื่องยนต์การเกษตร",
  "เครื่องตัดหญ้า",
  "เครื่องพ่นยา",
  "เครื่องพ่นปุ๋ย",
  "ปั๊มน้ำ / เครื่องสูบน้ำ",
  "เครื่องเจาะดิน",
  "เครื่องมือช่าง",
  "เครื่องมือเกษตรทั่วไป",
  "อุปกรณ์ตัดแต่งกิ่ง",
  "อุปกรณ์ระบบน้ำ",
  "อุปกรณ์ไฟฟ้า / โซลาร์เซลล์",
  "อุปกรณ์คลังสินค้า",
  "อุปกรณ์สำนักงาน",
  "อะไหล่และอุปกรณ์เสริม",
  "อื่น ๆ ระบุเอง",
];

const assetSizeOptions = ["ชิ้นเล็ก", "ชิ้นกลาง", "ชิ้นใหญ่"];
const assetStatusOptions = ["พร้อมใช้งาน", "ใช้งานอยู่", "ต้องตรวจเช็ค", "รอซ่อม", "ชำรุด", "สูญหาย", "เลิกใช้งาน"];
const checkCycleOptions = ["ตรวจทุกวัน", "ตรวจทุกสัปดาห์", "ตรวจทุกเดือน", "ตรวจตามชั่วโมงใช้งาน", "ตรวจตามระยะทาง", "กำหนดเอง"];
const checkResultOptions = ["ปกติ", "ต้องเฝ้าระวัง", "ต้องซ่อม", "ใช้งานไม่ได้"];
const vehicleTypeOptions = ["รถกระบะ", "รถไถ", "เครื่องยนต์", "เครื่องจักร", "อื่น ๆ"];

const assetExampleGroups = [
  { title: "อุปกรณ์ชิ้นเล็ก", items: ["จอบ", "เสียม", "คราด", "มีด", "กรรไกรตัดกิ่ง", "ถังพ่นยา", "บัวรดน้ำ", "สายยาง", "หัวน้ำหยด", "ข้อต่อ", "วาล์ว", "ประแจ", "คีม", "ไขควง", "เทปพันเกลียว"] },
  { title: "อุปกรณ์ชิ้นใหญ่", items: ["รถกระบะ", "รถไถ", "เครื่องตัดหญ้า", "เครื่องพ่นยา", "ปั๊มน้ำ", "เครื่องสูบน้ำ", "เครื่องเจาะดิน", "เครื่องปั่นไฟ", "ระบบโซลาร์เซลล์", "ถังเก็บน้ำ", "รถเข็น", "เครื่องย่อยกิ่งไม้"] },
];

const checklistsByType = {
  vehicle: ["น้ำมันเครื่อง", "น้ำหล่อเย็น", "น้ำมันเบรก", "น้ำมันพวงมาลัย", "แบตเตอรี่", "ยางรถยนต์", "ไฟหน้า / ไฟท้าย / ไฟเลี้ยว", "เบรก", "แตร", "ใบปัดน้ำฝน", "เลขไมล์", "น้ำมันเชื้อเพลิง", "ความสะอาดรถ", "ความเสียหายรอบตัวรถ", "อุปกรณ์ฉุกเฉินประจำรถ"],
  engine: ["น้ำมันเครื่อง", "น้ำมันเชื้อเพลิง", "กรองอากาศ", "หัวเทียน", "สายพาน", "น็อต / จุดยึด", "เสียงเครื่องผิดปกติ", "ควันผิดปกติ", "การรั่วซึม", "ความร้อนเครื่องยนต์", "การสตาร์ท", "ความพร้อมใช้งาน"],
  tool: ["สภาพตัวอุปกรณ์", "ความสะอาด", "ความคมของใบมีด", "ด้ามจับ / โครงสร้าง", "น็อตและจุดยึด", "สายไฟ / สายสะพาย / ท่อ", "มีรอยแตกหรือชำรุดหรือไม่", "ใช้งานได้ปกติหรือไม่", "ต้องซ่อมหรือเปลี่ยนอะไหล่หรือไม่"],
};

const initialAssetRegister = [
  { id: "CAR-001", name: "รถกระบะฟาร์ม", category: "รถยนต์ / รถกระบะ", size: "ชิ้นใหญ่", quantity: 1, unit: "คัน", owner: "คุณหวาน", storage: "ลานจอดโรงเรือน", status: "พร้อมใช้งาน", checkCycle: "ตรวจทุกวัน", lastCheck: "28 พ.ค. 2569", nextCheck: "29 พ.ค. 2569", image: "รูปหน้ารถ + เลขไมล์", note: "เลขไมล์ 82,450 กม. / น้ำมันดีเซล", maintenanceCost: 4200, vehicle: true, docs: "พรบ. ประกันภัย ใบซ่อม" },
  { id: "TRAC-002", name: "รถไถเล็ก", category: "รถไถ / รถแทรกเตอร์", size: "ชิ้นใหญ่", quantity: 1, unit: "คัน", owner: "พี่สมชาย", storage: "โกดังเครื่องจักร", status: "ต้องตรวจเช็ค", checkCycle: "ตรวจทุกสัปดาห์", lastCheck: "21 พ.ค. 2569", nextCheck: "28 พ.ค. 2569", image: "รูปด้านข้าง + ชั่วโมงเครื่อง", note: "ครบกำหนดเช็คสายพาน", maintenanceCost: 6800, vehicle: true, docs: "คู่มือรถไถ" },
  { id: "ENG-003", name: "เครื่องสูบน้ำดีเซล", category: "เครื่องยนต์การเกษตร", size: "ชิ้นใหญ่", quantity: 1, unit: "เครื่อง", owner: "พี่ไกร", storage: "บ่อน้ำ Zone 2", status: "รอซ่อม", checkCycle: "ตรวจตามชั่วโมงใช้งาน", lastCheck: "25 พ.ค. 2569", nextCheck: "30 พ.ค. 2569", image: "รูปจุดรั่วซึม", note: "พบคราบน้ำมัน ต้องติดตามร้านซ่อม", maintenanceCost: 12500, vehicle: true, docs: "ใบแจ้งซ่อม" },
  { id: "MOW-004", name: "เครื่องตัดหญ้า", category: "เครื่องตัดหญ้า", size: "ชิ้นกลาง", quantity: 3, unit: "เครื่อง", owner: "ทีมแปลง A", storage: "ห้องเครื่องมือ", status: "ใช้งานอยู่", checkCycle: "ตรวจทุกวัน", lastCheck: "28 พ.ค. 2569", nextCheck: "29 พ.ค. 2569", image: "รูปก่อนใช้งาน", note: "ใช้งานในแปลง A1-A36", maintenanceCost: 1600, vehicle: false, docs: "คู่มือเครื่องตัดหญ้า" },
  { id: "SPR-005", name: "เครื่องพ่นยาแบตเตอรี่", category: "เครื่องพ่นยา", size: "ชิ้นกลาง", quantity: 4, unit: "เครื่อง", owner: "พี่ไกร", storage: "คลังสารชีวภัณฑ์", status: "พร้อมใช้งาน", checkCycle: "ตรวจทุกสัปดาห์", lastCheck: "27 พ.ค. 2569", nextCheck: "3 มิ.ย. 2569", image: "รูปถังและสายพ่น", note: "ทำความสะอาดแล้ว", maintenanceCost: 900, vehicle: false, docs: "รูปใบเสร็จ" },
  { id: "PUMP-006", name: "ปั๊มน้ำไฟฟ้า", category: "ปั๊มน้ำ / เครื่องสูบน้ำ", size: "ชิ้นใหญ่", quantity: 2, unit: "เครื่อง", owner: "ทีมระบบน้ำ", storage: "โรงเรือนระบบน้ำ", status: "ชำรุด", checkCycle: "ตรวจทุกเดือน", lastCheck: "20 พ.ค. 2569", nextCheck: "20 มิ.ย. 2569", image: "รูปปั๊มน้ำ", note: "เครื่องที่ 2 สตาร์ทไม่ติด", maintenanceCost: 9800, vehicle: false, docs: "ใบเสนอราคาซ่อม" },
  { id: "TOOL-007", name: "กรรไกรตัดกิ่ง", category: "อุปกรณ์ตัดแต่งกิ่ง", size: "ชิ้นเล็ก", quantity: 12, unit: "ชิ้น", owner: "ทีมคนงาน", storage: "ชั้นเครื่องมือ 1", status: "พร้อมใช้งาน", checkCycle: "ตรวจทุกสัปดาห์", lastCheck: "27 พ.ค. 2569", nextCheck: "3 มิ.ย. 2569", image: "รูปชุดเครื่องมือ", note: "ลับคมแล้ว 8 ชิ้น", maintenanceCost: 450, vehicle: false, docs: "รูปหลังทำความสะอาด" },
  { id: "IRR-008", name: "ชุดหัวน้ำหยดและวาล์ว", category: "อุปกรณ์ระบบน้ำ", size: "ชิ้นเล็ก", quantity: 80, unit: "ชิ้น", owner: "ทีมระบบน้ำ", storage: "คลังอะไหล่ระบบน้ำ", status: "ต้องตรวจเช็ค", checkCycle: "ตรวจทุกสัปดาห์", lastCheck: "22 พ.ค. 2569", nextCheck: "28 พ.ค. 2569", image: "รูปกล่องอะไหล่", note: "ตรวจนับหลังซ่อมแปลง B", maintenanceCost: 350, vehicle: false, docs: "รายการเบิกอะไหล่" },
];

const initialAssetChecks = [
  { id: "CHK-001", date: "28 พ.ค. 2569", cycle: "รายวัน", asset: "รถกระบะฟาร์ม", inspector: "คุณหวาน", result: "ปกติ", issue: "ไม่พบปัญหา", evidence: "รูปเลขไมล์ + รูปหน้ารถ" },
  { id: "CHK-002", date: "28 พ.ค. 2569", cycle: "รายวัน", asset: "เครื่องตัดหญ้า", inspector: "พี่ไกร", result: "ต้องเฝ้าระวัง", issue: "ใบมีดเริ่มทื่อ", evidence: "รูปใบมีดก่อนลับคม" },
  { id: "CHK-003", date: "27 พ.ค. 2569", cycle: "รายสัปดาห์", asset: "กรรไกรตัดกิ่ง", inspector: "พี่สมชาย", result: "ปกติ", issue: "ทำความสะอาดครบ", evidence: "รูปหลังทำความสะอาด" },
];

const initialRepairTickets = [
  { id: "REP-001", asset: "เครื่องสูบน้ำดีเซล", priority: "เร่งด่วน", status: "รอซ่อม", owner: "พี่ไกร", due: "30 พ.ค. 2569", note: "คราบน้ำมันใต้เครื่อง ต้องเช็คร้านซ่อม" },
  { id: "REP-002", asset: "ปั๊มน้ำไฟฟ้า", priority: "สำคัญ", status: "ชำรุด", owner: "ทีมระบบน้ำ", due: "31 พ.ค. 2569", note: "เครื่องที่ 2 สตาร์ทไม่ติด" },
];

function AssetStatusBadge({ status }) {
  const styles = {
    "พร้อมใช้งาน": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
    "ใช้งานอยู่": "bg-blue-100 text-blue-700 ring-blue-200",
    "ต้องตรวจเช็ค": "bg-amber-100 text-amber-800 ring-amber-200",
    "รอซ่อม": "bg-orange-100 text-orange-800 ring-orange-200",
    "ชำรุด": "bg-red-100 text-red-700 ring-red-200",
    "สูญหาย": "bg-slate-200 text-slate-700 ring-slate-300",
    "เลิกใช้งาน": "bg-slate-100 text-slate-600 ring-slate-200",
  };
  return <Badge className={styles[status] || "bg-slate-100 text-slate-700 ring-slate-200"}>{status}</Badge>;
}

function AssetMetricCard({ label, value, hint, icon, tone = "green" }) {
  const tones = {
    green: "border-goodseed-100 bg-white text-goodseed-800",
    blue: "border-blue-100 bg-blue-50 text-blue-700",
    amber: "border-amber-100 bg-amber-50 text-amber-800",
    red: "border-red-100 bg-red-50 text-red-700",
    slate: "border-slate-100 bg-slate-50 text-slate-700",
  };
  return (
    <div className={`rounded-xl border p-4 shadow-soft ${tones[tone]}`}>
      <div className="flex items-center justify-between gap-3">
        <p className="text-xs font-extrabold text-slate-600">{label}</p>
        <span className="grid h-9 w-9 place-items-center rounded-lg bg-white/80"><Icon name={icon} className="h-5 w-5" /></span>
      </div>
      <p className="mt-2 whitespace-nowrap text-2xl font-extrabold text-goodseed-950">{value}</p>
      <p className="mt-1 text-xs font-bold text-slate-500">{hint}</p>
    </div>
  );
}

function getChecklistType(asset) {
  if (!asset) return "tool";
  if (asset.vehicle || asset.category.includes("รถ")) return "vehicle";
  if (asset.category.includes("เครื่องยนต์") || asset.category.includes("เครื่อง") || asset.category.includes("ปั๊ม")) return "engine";
  return "tool";
}

function FarmAssetsPage({ role = "owner" }) {
  const canManageMaster = ["owner", "admin", "manager"].includes(role);
  const canCheck = ["owner", "admin", "manager", "staff"].includes(role);
  const canExport = ["owner", "admin", "manager"].includes(role);
  const [assetRows, setAssetRows] = useState(initialAssetRegister);
  const [checkRows, setCheckRows] = useState(initialAssetChecks);
  const [repairRows, setRepairRows] = useState(initialRepairTickets);
  const [activePanel, setActivePanel] = useState("dashboard");
  const [query, setQuery] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("ทั้งหมด");
  const [sizeFilter, setSizeFilter] = useState("ทั้งหมด");
  const [statusFilter, setStatusFilter] = useState("ทั้งหมด");
  const [cycleFilter, setCycleFilter] = useState("ทั้งหมด");
  const [ownerFilter, setOwnerFilter] = useState("ทั้งหมด");
  const [notice, setNotice] = useState("ระบบพร้อมบันทึกข้อมูลอุปกรณ์ รถยนต์ เครื่องยนต์ และเครื่องมือการเกษตร");
  const [equipmentForm, setEquipmentForm] = useState({
    id: "ASSET-NEW",
    name: "",
    category: "เครื่องมือเกษตรทั่วไป",
    size: "ชิ้นเล็ก",
    other: "",
    brand: "",
    model: "",
    serial: "",
    quantity: "1",
    unit: "ชิ้น",
    purchaseDate: "",
    purchasePrice: "",
    supplier: "",
    owner: "",
    storage: "",
    purpose: "",
    status: "พร้อมใช้งาน",
    checkCycle: "ตรวจทุกสัปดาห์",
    note: "",
    photo: "",
    receipt: "",
    manual: "",
  });
  const [vehicleForm, setVehicleForm] = useState({
    id: "VEH-NEW",
    type: "รถกระบะ",
    other: "",
    brand: "",
    model: "",
    year: "",
    plate: "",
    chassis: "",
    engineNo: "",
    fuel: "ดีเซล",
    mileage: "",
    hours: "",
    purchaseDate: "",
    purchasePrice: "",
    owner: "",
    parking: "",
    compulsoryExpiry: "",
    insuranceExpiry: "",
    taxDate: "",
    inspectionDate: "",
    frontPhoto: "",
    sidePhoto: "",
    platePhoto: "",
    mileagePhoto: "",
    docs: "",
  });
  const [checkForm, setCheckForm] = useState({
    date: "28 พ.ค. 2569",
    cycle: "รายวัน",
    assetId: initialAssetRegister[0].id,
    inspector: "คุณหวาน",
    beforeStatus: "พร้อมใช้งาน",
    result: "ปกติ",
    issue: "",
    fix: "",
    repairRequired: "ไม่ต้องแจ้งซ่อม",
    followOwner: "",
    repeatDate: "",
    beforePhoto: "",
    duringPhoto: "",
    afterPhoto: "",
    note: "",
  });
  const [checkedItems, setCheckedItems] = useState(["น้ำมันเครื่อง", "น้ำหล่อเย็น", "ยางรถยนต์"]);
  const [repairForm, setRepairForm] = useState({ assetId: initialAssetRegister[2].id, priority: "สำคัญ", owner: "พี่ไกร", due: "", note: "", photo: "", receipt: "" });

  if (role === "customer") {
    return <section className="rounded-xl border border-goodseed-100 bg-white p-6 shadow-soft"><p className="font-extrabold text-goodseed-900">หน้านี้เป็นข้อมูลภายใน ไม่เปิดให้ Customer/Public ใช้งาน</p></section>;
  }

  const selectedAsset = assetRows.find((item) => item.id === checkForm.assetId) || assetRows[0];
  const checklistType = getChecklistType(selectedAsset);
  const currentChecklist = checklistsByType[checklistType];
  const ownerOptions = ["ทั้งหมด", ...Array.from(new Set(assetRows.map((item) => item.owner).filter(Boolean)))];
  const filteredAssets = assetRows.filter((item) => {
    const matchText = [item.id, item.name, item.category, item.owner, item.storage, item.note].join(" ").toLowerCase().includes(query.toLowerCase());
    return matchText
      && (categoryFilter === "ทั้งหมด" || item.category === categoryFilter)
      && (sizeFilter === "ทั้งหมด" || item.size === sizeFilter)
      && (statusFilter === "ทั้งหมด" || item.status === statusFilter)
      && (cycleFilter === "ทั้งหมด" || item.checkCycle === cycleFilter)
      && (ownerFilter === "ทั้งหมด" || item.owner === ownerFilter);
  });

  const metrics = {
    total: assetRows.length,
    vehicles: assetRows.filter((item) => item.vehicle || item.category.includes("รถ") || item.category.includes("เครื่องยนต์")).length,
    small: assetRows.filter((item) => item.size === "ชิ้นเล็ก").length,
    large: assetRows.filter((item) => item.size === "ชิ้นใหญ่").length,
    ready: assetRows.filter((item) => item.status === "พร้อมใช้งาน").length,
    dueToday: assetRows.filter((item) => ["28 พ.ค. 2569", "วันนี้"].includes(item.nextCheck)).length,
    checkedToday: checkRows.filter((item) => item.date === "28 พ.ค. 2569").length,
    overdue: assetRows.filter((item) => item.status === "ต้องตรวจเช็ค").length,
    repair: assetRows.filter((item) => item.status === "รอซ่อม").length,
    broken: assetRows.filter((item) => item.status === "ชำรุด").length,
    cost: assetRows.reduce((sum, item) => sum + (item.maintenanceCost || 0), 0),
  };

  const exportAssets = () => {
    const heads = ["รหัสอุปกรณ์", "ชื่ออุปกรณ์", "ประเภท", "ขนาด", "จำนวน", "ผู้รับผิดชอบ", "สถานที่จัดเก็บ", "สถานะ", "รอบตรวจ", "วันที่ตรวจล่าสุด", "วันที่ต้องตรวจครั้งถัดไป", "หมายเหตุ"];
    const rows = assetRows.map((item) => [item.id, item.name, item.category, item.size, item.quantity, item.owner, item.storage, item.status, item.checkCycle, item.lastCheck, item.nextCheck, item.note]);
    downloadFile("goodseed-equipment-vehicle.csv", "\ufeff" + [heads, ...rows].map((row) => row.map((cell) => `"${String(cell).replaceAll('"', '""')}"`).join(",")).join("\n"), "text/csv;charset=utf-8");
  };

  const saveEquipment = () => {
    if (!canManageMaster) return setNotice("Staff สามารถบันทึกตรวจเช็คและแจ้งซ่อมได้ แต่แก้ไขทะเบียนหลักไม่ได้");
    const category = equipmentForm.category === "อื่น ๆ ระบุเอง" ? equipmentForm.other || "อื่น ๆ" : equipmentForm.category;
    const newAsset = {
      id: equipmentForm.id || `ASSET-${assetRows.length + 1}`,
      name: equipmentForm.name || "รายการอุปกรณ์ใหม่",
      category,
      size: equipmentForm.size,
      quantity: Number(equipmentForm.quantity || 1),
      unit: equipmentForm.unit || "ชิ้น",
      owner: equipmentForm.owner || "ยังไม่ระบุ",
      storage: equipmentForm.storage || "คลังกลาง",
      status: equipmentForm.status,
      checkCycle: equipmentForm.checkCycle,
      lastCheck: "-",
      nextCheck: "กำหนดหลังบันทึก",
      image: equipmentForm.photo || "รอแนบรูป",
      note: [equipmentForm.brand, equipmentForm.model, equipmentForm.serial, equipmentForm.purpose, equipmentForm.note].filter(Boolean).join(" / ") || "เพิ่มจากฟอร์มทะเบียนอุปกรณ์",
      maintenanceCost: 0,
      vehicle: false,
      docs: [equipmentForm.receipt, equipmentForm.manual].filter(Boolean).join(" / ") || "รอแนบเอกสาร",
    };
    setAssetRows((rows) => [newAsset, ...rows]);
    setNotice(`บันทึกอุปกรณ์ใหม่แล้ว: ${newAsset.name}`);
    setActivePanel("register");
  };

  const saveVehicle = () => {
    if (!canManageMaster) return setNotice("Staff สามารถบันทึกตรวจเช็คและแจ้งซ่อมได้ แต่แก้ไขทะเบียนรถ/เครื่องยนต์หลักไม่ได้");
    const type = vehicleForm.type === "อื่น ๆ" ? vehicleForm.other || "เครื่องจักร" : vehicleForm.type;
    const newVehicle = {
      id: vehicleForm.id || `VEH-${assetRows.length + 1}`,
      name: `${type} ${vehicleForm.brand || ""} ${vehicleForm.model || ""}`.trim() || "รถยนต์ / เครื่องยนต์ใหม่",
      category: type === "รถกระบะ" ? "รถยนต์ / รถกระบะ" : type === "รถไถ" ? "รถไถ / รถแทรกเตอร์" : "เครื่องยนต์การเกษตร",
      size: "ชิ้นใหญ่",
      quantity: 1,
      unit: type.includes("รถ") ? "คัน" : "เครื่อง",
      owner: vehicleForm.owner || "ยังไม่ระบุ",
      storage: vehicleForm.parking || "ลานจอด / โกดังเครื่องจักร",
      status: "พร้อมใช้งาน",
      checkCycle: "ตรวจทุกวัน",
      lastCheck: "-",
      nextCheck: "กำหนดหลังบันทึก",
      image: [vehicleForm.frontPhoto, vehicleForm.sidePhoto, vehicleForm.platePhoto, vehicleForm.mileagePhoto].filter(Boolean).join(" / ") || "รอแนบรูป",
      note: [`ทะเบียน ${vehicleForm.plate || "-"}`, `เลขไมล์ ${vehicleForm.mileage || "-"}`, `ชั่วโมงเครื่อง ${vehicleForm.hours || "-"}`, `น้ำมัน ${vehicleForm.fuel}`].join(" / "),
      maintenanceCost: 0,
      vehicle: true,
      docs: vehicleForm.docs || "รอแนบเอกสารรถ",
    };
    setAssetRows((rows) => [newVehicle, ...rows]);
    setNotice(`บันทึกทะเบียนรถ/เครื่องยนต์แล้ว: ${newVehicle.name}`);
    setActivePanel("register");
  };

  const saveCheck = () => {
    if (!canCheck) return;
    const assetName = selectedAsset?.name || "อุปกรณ์";
    const newCheck = {
      id: `CHK-${String(checkRows.length + 1).padStart(3, "0")}`,
      date: checkForm.date,
      cycle: checkForm.cycle,
      asset: assetName,
      inspector: checkForm.inspector,
      result: checkForm.result,
      issue: checkForm.issue || "ไม่พบปัญหา",
      evidence: [checkForm.beforePhoto, checkForm.duringPhoto, checkForm.afterPhoto].filter(Boolean).join(" / ") || "แนบรูปภายหลัง",
    };
    setCheckRows((rows) => [newCheck, ...rows]);
    setAssetRows((rows) => rows.map((item) => item.id === checkForm.assetId ? { ...item, lastCheck: checkForm.date, status: checkForm.result === "ใช้งานไม่ได้" ? "ชำรุด" : checkForm.result === "ต้องซ่อม" ? "รอซ่อม" : checkForm.result === "ต้องเฝ้าระวัง" ? "ต้องตรวจเช็ค" : "พร้อมใช้งาน" } : item));
    if (checkForm.repairRequired === "ต้องแจ้งซ่อม") {
      setRepairRows((rows) => [{ id: `REP-${String(rows.length + 1).padStart(3, "0")}`, asset: assetName, priority: "สำคัญ", status: "รอซ่อม", owner: checkForm.followOwner || checkForm.inspector, due: checkForm.repeatDate || "รอกำหนด", note: checkForm.issue || "แจ้งซ่อมจากผลตรวจเช็ค" }, ...rows]);
    }
    setNotice(`บันทึกการตรวจเช็ค ${assetName} แล้ว`);
    setActivePanel("history");
  };

  const saveRepair = () => {
    const asset = assetRows.find((item) => item.id === repairForm.assetId);
    setRepairRows((rows) => [{ id: `REP-${String(rows.length + 1).padStart(3, "0")}`, asset: asset?.name || "อุปกรณ์", priority: repairForm.priority, status: "รอซ่อม", owner: repairForm.owner, due: repairForm.due || "รอกำหนด", note: repairForm.note || "แจ้งซ่อมจากฟอร์ม" }, ...rows]);
    setAssetRows((rows) => rows.map((item) => item.id === repairForm.assetId ? { ...item, status: "รอซ่อม" } : item));
    setNotice(`ส่งรายการแจ้งซ่อมแล้ว: ${asset?.name || "อุปกรณ์"}`);
    setActivePanel("repair");
  };

  const openAssetPanel = (panel) => {
    const panelMessages = {
      dashboard: "เปิดภาพรวมอุปกรณ์และรถยนต์",
      register: "เปิดรายการทะเบียนอุปกรณ์และรถยนต์ทั้งหมด",
      "equipment-form": "เปิดฟอร์มเพิ่มอุปกรณ์ใหม่ กรอกข้อมูลแล้วกดบันทึกอุปกรณ์ใหม่ได้ทันที",
      "vehicle-form": "เปิดฟอร์มเพิ่มรถยนต์ / เครื่องยนต์ กรอกทะเบียนและเอกสารประจำรถได้",
      check: "เปิดฟอร์มบันทึกการตรวจเช็ค เลือกอุปกรณ์แล้วบันทึกผลตรวจได้",
      history: "เปิดประวัติการตรวจเช็คย้อนหลัง",
      repair: "เปิดฟอร์มแจ้งซ่อมและรายการซ่อมที่ต้องติดตาม",
      evidence: "เปิดคลังเอกสารและรูปถ่ายหลักฐานของอุปกรณ์",
    };
    setActivePanel(panel);
    setNotice(panelMessages[panel] || "เปิดเมนูอุปกรณ์และรถยนต์แล้ว");
    window.setTimeout(() => document.getElementById("equipment-action-panel")?.scrollIntoView({ behavior: "smooth", block: "start" }), 0);
  };

  const tabs = [
    ["dashboard", "Dashboard"],
    ["register", "รายการทั้งหมด"],
    ["equipment-form", "เพิ่มอุปกรณ์ใหม่"],
    ["vehicle-form", "เพิ่มรถยนต์ / เครื่องยนต์"],
    ["check", "บันทึกตรวจเช็ค"],
    ["history", "ประวัติตรวจเช็ค"],
    ["repair", "แจ้งซ่อม"],
    ["evidence", "เอกสารและรูปถ่าย"],
  ];

  return (
    <section id="equipment" className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4 shadow-soft xl:col-span-3">
      <SectionHeader
        title="อุปกรณ์และรถยนต์"
        subtitle="ทะเบียนทรัพย์สินฟาร์ม รถยนต์ เครื่องยนต์ เครื่องมือเกษตร ตารางตรวจเช็ค หลักฐานรูปถ่าย และระบบแจ้งซ่อม"
        action={<div className="flex flex-wrap gap-2">
          {canManageMaster && <button type="button" onClick={() => openAssetPanel("equipment-form")} className="rounded-lg bg-goodseed-700 px-3 py-2 text-sm font-extrabold text-white shadow-sm">+ เพิ่มอุปกรณ์ใหม่</button>}
          {canManageMaster && <button type="button" onClick={() => openAssetPanel("vehicle-form")} className="rounded-lg bg-white px-3 py-2 text-sm font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">+ เพิ่มรถยนต์ / เครื่องยนต์</button>}
          <button type="button" onClick={() => openAssetPanel("check")} className="rounded-lg bg-white px-3 py-2 text-sm font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">บันทึกการตรวจเช็ค</button>
          <button type="button" onClick={() => openAssetPanel("repair")} className="rounded-lg bg-white px-3 py-2 text-sm font-extrabold text-red-700 ring-1 ring-red-100">แจ้งซ่อม</button>
          {canExport && <button type="button" onClick={exportAssets} className="rounded-lg bg-white px-3 py-2 text-sm font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">Export Excel</button>}
        </div>}
      />

      <CrudGovernanceBar role={role} moduleId="equipment" title="Equipment & Vehicle CRUD" />

      <div className="mb-4 rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-bold text-goodseed-800 shadow-sm">{notice}</div>

      <div className="mb-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6">
        <AssetMetricCard label="อุปกรณ์ทั้งหมด" value={`${metrics.total} รายการ`} hint="รวมทะเบียนทั้งหมด" icon="assets" />
        <AssetMetricCard label="รถยนต์ / เครื่องยนต์" value={`${metrics.vehicles} รายการ`} hint="รถและเครื่องจักรหลัก" icon="truck" tone="blue" />
        <AssetMetricCard label="อุปกรณ์ชิ้นเล็ก" value={`${metrics.small} รายการ`} hint="เครื่องมือเกษตรทั่วไป" icon="wrench" />
        <AssetMetricCard label="อุปกรณ์ชิ้นใหญ่" value={`${metrics.large} รายการ`} hint="ทรัพย์สินถาวร" icon="settings" tone="blue" />
        <AssetMetricCard label="พร้อมใช้งาน" value={`${metrics.ready} รายการ`} hint="ตรวจผ่านล่าสุด" icon="check" />
        <AssetMetricCard label="ต้องตรวจวันนี้" value={`${metrics.dueToday} รายการ`} hint="ตามรอบตรวจ" icon="calendar" tone="amber" />
        <AssetMetricCard label="ตรวจแล้ววันนี้" value={`${metrics.checkedToday} รายการ`} hint="มีประวัติตรวจเช็ค" icon="file" />
        <AssetMetricCard label="ค้างตรวจ" value={`${metrics.overdue} รายการ`} hint="ต้องติดตาม" icon="bell" tone="amber" />
        <AssetMetricCard label="รอซ่อม" value={`${metrics.repair} รายการ`} hint="เปิด ticket แล้ว" icon="wrench" tone="red" />
        <AssetMetricCard label="ชำรุด" value={`${metrics.broken} รายการ`} hint="ใช้งานไม่ได้" icon="wrench" tone="red" />
        <AssetMetricCard label="ค่าซ่อมเดือนนี้" value={`${metrics.cost.toLocaleString("th-TH")} บาท`} hint="PM + ซ่อมบำรุง" icon="money" tone="slate" />
      </div>

      <div className="no-print mb-5 flex gap-2 overflow-x-auto pb-1">
        {tabs.map(([id, label]) => <button key={id} type="button" onClick={() => openAssetPanel(id)} className={`whitespace-nowrap rounded-lg px-4 py-2 text-sm font-extrabold transition ${activePanel === id ? "bg-goodseed-800 text-white shadow-soft" : "bg-white text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-50"}`}>{label}</button>)}
      </div>

      <div id="equipment-action-panel" className="scroll-mt-28">
      {activePanel === "dashboard" && (
        <div className="grid gap-5 xl:grid-cols-[1.1fr_0.9fr]">
          <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
            <h3 className="text-xl font-extrabold text-goodseed-950">ภาพรวมทะเบียนอุปกรณ์และรถยนต์</h3>
            <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">รองรับตั้งแต่เครื่องมือชิ้นเล็ก เช่น จอบ เสียม กรรไกรตัดกิ่ง จนถึงรถกระบะ รถไถ ปั๊มน้ำ เครื่องยนต์ เครื่องจักร และสินทรัพย์ใหม่ในอนาคต</p>
            <div className="mt-5 grid gap-4 lg:grid-cols-2">
              {assetExampleGroups.map((group) => (
                <div key={group.title} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4">
                  <p className="font-extrabold text-goodseed-900">{group.title}</p>
                  <div className="mt-3 flex flex-wrap gap-2">{group.items.map((item) => <Badge key={item} className="bg-white text-goodseed-800 ring-goodseed-200">{item}</Badge>)}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
            <div className="flex items-center justify-between gap-3">
              <h3 className="text-xl font-extrabold text-goodseed-950">แจ้งเตือนและติดตาม</h3>
              <Badge className="bg-red-100 text-red-700 ring-red-200">{repairRows.length} งานซ่อม</Badge>
            </div>
            <div className="mt-4 space-y-3">
              {[
                ["ต้องตรวจวันนี้", "ชุดหัวน้ำหยดและวาล์ว / รถไถเล็ก", "สำคัญ"],
                ["ค้างตรวจ", "อุปกรณ์ระบบน้ำแปลง B", "ต้องติดตาม"],
                ["รอซ่อม", "เครื่องสูบน้ำดีเซล / ปั๊มน้ำไฟฟ้า", "เร่งด่วน"],
                ["รถใกล้ครบกำหนด", "ตรวจ พ.ร.บ. / ประกันภัยก่อนสิ้นเดือน", "ปานกลาง"],
                ["ต้องตรวจซ้ำ", "เครื่องตัดหญ้าใบมีดเริ่มทื่อ", "เฝ้าระวัง"],
              ].map(([title, detail, level]) => (
                <div key={title} className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-3">
                  <div className="flex items-start justify-between gap-3">
                    <div><p className="font-extrabold text-goodseed-900">{title}</p><p className="mt-1 text-sm font-semibold text-goodseed-700">{detail}</p></div>
                    <Badge className={level === "เร่งด่วน" ? "bg-red-100 text-red-700 ring-red-200" : "bg-amber-100 text-amber-800 ring-amber-200"}>{level}</Badge>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {activePanel === "register" && (
        <div className="rounded-xl border border-goodseed-100 bg-white p-4 shadow-soft">
          <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-6">
            <label className="xl:col-span-2"><span className="text-sm font-bold text-goodseed-800">Search ค้นหาชื่ออุปกรณ์ รหัส หรือทะเบียนรถ</span><input value={query} onChange={(event) => setQuery(event.target.value)} className="mt-2 w-full rounded-lg border border-goodseed-200 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-goodseed-300" placeholder="เช่น CAR-001, รถกระบะ, ปั๊มน้ำ" /></label>
            <Select label="ประเภท" value={categoryFilter} onChange={setCategoryFilter} options={["ทั้งหมด", ...assetCategoryOptions]} />
            <Select label="ขนาด" value={sizeFilter} onChange={setSizeFilter} options={["ทั้งหมด", ...assetSizeOptions]} />
            <Select label="สถานะ" value={statusFilter} onChange={setStatusFilter} options={["ทั้งหมด", ...assetStatusOptions]} />
            <Select label="รอบตรวจ" value={cycleFilter} onChange={setCycleFilter} options={["ทั้งหมด", ...checkCycleOptions]} />
            <Select label="ผู้รับผิดชอบ" value={ownerFilter} onChange={setOwnerFilter} options={ownerOptions} />
          </div>
          <div className="mt-5 hidden overflow-x-auto rounded-xl border border-goodseed-100 lg:block">
            <table className="min-w-[1500px] w-full text-left text-sm">
              <thead className="bg-goodseed-50 text-goodseed-800"><tr>{["รหัสอุปกรณ์", "ชื่ออุปกรณ์", "ประเภท", "ขนาด", "จำนวน", "ผู้รับผิดชอบ", "สถานที่จัดเก็บ", "สถานะ", "รอบตรวจ", "ตรวจล่าสุด", "ตรวจครั้งถัดไป", "รูปอุปกรณ์", "รายละเอียด", "ตรวจเช็ค", "แจ้งซ่อม"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr></thead>
              <tbody className="divide-y divide-goodseed-100 bg-white">
                {filteredAssets.map((item) => (
                  <tr key={item.id} className="align-top">
                    <td className="px-3 py-3 font-extrabold text-goodseed-900">{item.id}</td>
                    <td className="px-3 py-3 font-extrabold text-goodseed-950">{item.name}</td>
                    <td className="px-3 py-3 text-goodseed-700">{item.category}</td>
                    <td className="px-3 py-3">{item.size}</td>
                    <td className="px-3 py-3">{item.quantity} {item.unit}</td>
                    <td className="px-3 py-3">{item.owner}</td>
                    <td className="px-3 py-3">{item.storage}</td>
                    <td className="px-3 py-3"><AssetStatusBadge status={item.status} /></td>
                    <td className="px-3 py-3">{item.checkCycle}</td>
                    <td className="px-3 py-3">{item.lastCheck}</td>
                    <td className="px-3 py-3">{item.nextCheck}</td>
                    <td className="px-3 py-3"><span className="inline-flex items-center gap-2 text-xs font-bold text-goodseed-700"><Icon name="camera" className="h-4 w-4" />{item.image}</span></td>
                    <td className="px-3 py-3"><button onClick={() => setNotice(`${item.id}: ${item.note} / เอกสาร: ${item.docs}`)} className="rounded-lg bg-goodseed-50 px-3 py-1.5 text-xs font-extrabold text-goodseed-800">ดูรายละเอียด</button></td>
                    <td className="px-3 py-3"><button type="button" onClick={() => { setCheckForm((form) => ({ ...form, assetId: item.id, beforeStatus: item.status })); openAssetPanel("check"); }} className="rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-extrabold text-blue-700">บันทึกตรวจเช็ค</button></td>
                    <td className="px-3 py-3"><button type="button" onClick={() => { setRepairForm((form) => ({ ...form, assetId: item.id, owner: item.owner })); openAssetPanel("repair"); }} className="rounded-lg bg-red-50 px-3 py-1.5 text-xs font-extrabold text-red-700">แจ้งซ่อม</button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="mt-5 grid gap-3 lg:hidden">
            {filteredAssets.map((item) => (
              <div key={item.id} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4">
                <div className="flex items-start justify-between gap-3"><div><p className="text-xs font-extrabold text-goodseed-600">{item.id}</p><p className="text-lg font-extrabold text-goodseed-950">{item.name}</p></div><AssetStatusBadge status={item.status} /></div>
                <div className="mt-3 grid grid-cols-2 gap-2 text-xs font-bold text-goodseed-700">
                  <span className="rounded-lg bg-white p-2">ประเภท: {item.category}</span><span className="rounded-lg bg-white p-2">จำนวน: {item.quantity} {item.unit}</span><span className="rounded-lg bg-white p-2">ผู้รับผิดชอบ: {item.owner}</span><span className="rounded-lg bg-white p-2">ตรวจถัดไป: {item.nextCheck}</span>
                </div>
                <div className="mt-3 flex gap-2"><button type="button" onClick={() => { setCheckForm((form) => ({ ...form, assetId: item.id, beforeStatus: item.status })); openAssetPanel("check"); }} className="flex-1 rounded-lg bg-blue-600 px-3 py-2 text-xs font-extrabold text-white">ตรวจเช็ค</button><button type="button" onClick={() => { setRepairForm((form) => ({ ...form, assetId: item.id, owner: item.owner })); openAssetPanel("repair"); }} className="flex-1 rounded-lg bg-red-50 px-3 py-2 text-xs font-extrabold text-red-700">แจ้งซ่อม</button></div>
              </div>
            ))}
          </div>
        </div>
      )}

      {activePanel === "equipment-form" && (
        <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
          <h3 className="text-xl font-extrabold text-goodseed-950">ฟอร์มเพิ่มอุปกรณ์ใหม่</h3>
          {!canManageMaster && <p className="mt-2 rounded-lg bg-amber-50 p-3 text-sm font-bold text-amber-800">Role Staff ดูข้อมูล บันทึกตรวจเช็ค แนบรูป และแจ้งปัญหาได้ แต่แก้ไขทะเบียนหลักไม่ได้</p>}
          <div className="mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            <Input label="รหัสอุปกรณ์ / Asset ID" value={equipmentForm.id} onChange={(value) => setEquipmentForm({ ...equipmentForm, id: value })} />
            <Input label="ชื่ออุปกรณ์" value={equipmentForm.name} onChange={(value) => setEquipmentForm({ ...equipmentForm, name: value })} />
            <Select label="ประเภทอุปกรณ์" value={equipmentForm.category} onChange={(value) => setEquipmentForm({ ...equipmentForm, category: value })} options={assetCategoryOptions} />
            {equipmentForm.category === "อื่น ๆ ระบุเอง" && <Input label="อื่น ๆ ระบุเอง" value={equipmentForm.other} onChange={(value) => setEquipmentForm({ ...equipmentForm, other: value })} />}
            <Select label="ขนาดอุปกรณ์" value={equipmentForm.size} onChange={(value) => setEquipmentForm({ ...equipmentForm, size: value })} options={assetSizeOptions} />
            <Input label="ยี่ห้อ" value={equipmentForm.brand} onChange={(value) => setEquipmentForm({ ...equipmentForm, brand: value })} />
            <Input label="รุ่น" value={equipmentForm.model} onChange={(value) => setEquipmentForm({ ...equipmentForm, model: value })} />
            <Input label="หมายเลขเครื่อง / Serial Number" value={equipmentForm.serial} onChange={(value) => setEquipmentForm({ ...equipmentForm, serial: value })} />
            <Input label="จำนวน" value={equipmentForm.quantity} onChange={(value) => setEquipmentForm({ ...equipmentForm, quantity: value })} />
            <Input label="หน่วยนับ" value={equipmentForm.unit} onChange={(value) => setEquipmentForm({ ...equipmentForm, unit: value })} />
            <Input label="วันที่ซื้อ" value={equipmentForm.purchaseDate} onChange={(value) => setEquipmentForm({ ...equipmentForm, purchaseDate: value })} />
            <Input label="ราคาซื้อ" value={equipmentForm.purchasePrice} onChange={(value) => setEquipmentForm({ ...equipmentForm, purchasePrice: value })} />
            <Input label="ผู้ขาย / ร้านค้า" value={equipmentForm.supplier} onChange={(value) => setEquipmentForm({ ...equipmentForm, supplier: value })} />
            <Input label="ผู้รับผิดชอบ" value={equipmentForm.owner} onChange={(value) => setEquipmentForm({ ...equipmentForm, owner: value })} />
            <Input label="สถานที่จัดเก็บ" value={equipmentForm.storage} onChange={(value) => setEquipmentForm({ ...equipmentForm, storage: value })} />
            <Input label="ใช้สำหรับงานอะไร" value={equipmentForm.purpose} onChange={(value) => setEquipmentForm({ ...equipmentForm, purpose: value })} />
            <Select label="สถานะอุปกรณ์" value={equipmentForm.status} onChange={(value) => setEquipmentForm({ ...equipmentForm, status: value })} options={assetStatusOptions} />
            <Select label="รอบการตรวจเช็ค" value={equipmentForm.checkCycle} onChange={(value) => setEquipmentForm({ ...equipmentForm, checkCycle: value })} options={checkCycleOptions} />
            <Input label="แนบรูปอุปกรณ์" value={equipmentForm.photo} onChange={(value) => setEquipmentForm({ ...equipmentForm, photo: value })} />
            <Input label="แนบใบเสร็จ" value={equipmentForm.receipt} onChange={(value) => setEquipmentForm({ ...equipmentForm, receipt: value })} />
            <Input label="แนบคู่มือการใช้งาน" value={equipmentForm.manual} onChange={(value) => setEquipmentForm({ ...equipmentForm, manual: value })} />
            <Textarea label="หมายเหตุ" value={equipmentForm.note} onChange={(value) => setEquipmentForm({ ...equipmentForm, note: value })} wide />
          </div>
          <button onClick={saveEquipment} className="mt-5 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-soft">บันทึกอุปกรณ์ใหม่</button>
        </div>
      )}

      {activePanel === "vehicle-form" && (
        <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
          <h3 className="text-xl font-extrabold text-goodseed-950">ฟอร์มเพิ่มรถยนต์ / เครื่องยนต์</h3>
          <div className="mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            <Input label="รหัสรถ / รหัสเครื่องยนต์" value={vehicleForm.id} onChange={(value) => setVehicleForm({ ...vehicleForm, id: value })} />
            <Select label="ประเภท" value={vehicleForm.type} onChange={(value) => setVehicleForm({ ...vehicleForm, type: value })} options={vehicleTypeOptions} />
            {vehicleForm.type === "อื่น ๆ" && <Input label="อื่น ๆ ระบุเอง" value={vehicleForm.other} onChange={(value) => setVehicleForm({ ...vehicleForm, other: value })} />}
            <Input label="ยี่ห้อ" value={vehicleForm.brand} onChange={(value) => setVehicleForm({ ...vehicleForm, brand: value })} />
            <Input label="รุ่น" value={vehicleForm.model} onChange={(value) => setVehicleForm({ ...vehicleForm, model: value })} />
            <Input label="ปีที่ผลิต" value={vehicleForm.year} onChange={(value) => setVehicleForm({ ...vehicleForm, year: value })} />
            <Input label="เลขทะเบียนรถ" value={vehicleForm.plate} onChange={(value) => setVehicleForm({ ...vehicleForm, plate: value })} />
            <Input label="เลขตัวถัง" value={vehicleForm.chassis} onChange={(value) => setVehicleForm({ ...vehicleForm, chassis: value })} />
            <Input label="เลขเครื่องยนต์" value={vehicleForm.engineNo} onChange={(value) => setVehicleForm({ ...vehicleForm, engineNo: value })} />
            <Input label="น้ำมันที่ใช้" value={vehicleForm.fuel} onChange={(value) => setVehicleForm({ ...vehicleForm, fuel: value })} />
            <Input label="เลขไมล์ปัจจุบัน" value={vehicleForm.mileage} onChange={(value) => setVehicleForm({ ...vehicleForm, mileage: value })} />
            <Input label="ชั่วโมงเครื่องยนต์" value={vehicleForm.hours} onChange={(value) => setVehicleForm({ ...vehicleForm, hours: value })} />
            <Input label="วันที่ซื้อ" value={vehicleForm.purchaseDate} onChange={(value) => setVehicleForm({ ...vehicleForm, purchaseDate: value })} />
            <Input label="ราคาซื้อ" value={vehicleForm.purchasePrice} onChange={(value) => setVehicleForm({ ...vehicleForm, purchasePrice: value })} />
            <Input label="ผู้รับผิดชอบหลัก" value={vehicleForm.owner} onChange={(value) => setVehicleForm({ ...vehicleForm, owner: value })} />
            <Input label="สถานที่จอด / สถานที่เก็บ" value={vehicleForm.parking} onChange={(value) => setVehicleForm({ ...vehicleForm, parking: value })} />
            <Input label="วันหมดอายุ พ.ร.บ." value={vehicleForm.compulsoryExpiry} onChange={(value) => setVehicleForm({ ...vehicleForm, compulsoryExpiry: value })} />
            <Input label="วันหมดอายุประกันภัย" value={vehicleForm.insuranceExpiry} onChange={(value) => setVehicleForm({ ...vehicleForm, insuranceExpiry: value })} />
            <Input label="วันต่อภาษี" value={vehicleForm.taxDate} onChange={(value) => setVehicleForm({ ...vehicleForm, taxDate: value })} />
            <Input label="วันตรวจสภาพ" value={vehicleForm.inspectionDate} onChange={(value) => setVehicleForm({ ...vehicleForm, inspectionDate: value })} />
            <Input label="แนบรูปหน้ารถ" value={vehicleForm.frontPhoto} onChange={(value) => setVehicleForm({ ...vehicleForm, frontPhoto: value })} />
            <Input label="แนบรูปด้านข้าง" value={vehicleForm.sidePhoto} onChange={(value) => setVehicleForm({ ...vehicleForm, sidePhoto: value })} />
            <Input label="แนบรูปเลขทะเบียน" value={vehicleForm.platePhoto} onChange={(value) => setVehicleForm({ ...vehicleForm, platePhoto: value })} />
            <Input label="แนบรูปเลขไมล์" value={vehicleForm.mileagePhoto} onChange={(value) => setVehicleForm({ ...vehicleForm, mileagePhoto: value })} />
            <Input label="แนบเอกสารรถ" value={vehicleForm.docs} onChange={(value) => setVehicleForm({ ...vehicleForm, docs: value })} />
          </div>
          <button onClick={saveVehicle} className="mt-5 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-soft">บันทึกรถยนต์ / เครื่องยนต์</button>
        </div>
      )}

      {activePanel === "check" && (
        <div className="grid gap-5 xl:grid-cols-[0.85fr_1.15fr]">
          <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
            <h3 className="text-xl font-extrabold text-goodseed-950">ฟอร์มบันทึกการตรวจเช็ค</h3>
            <div className="mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-1">
              <Input label="วันที่ตรวจ" value={checkForm.date} onChange={(value) => setCheckForm({ ...checkForm, date: value })} />
              <Select label="รอบการตรวจ" value={checkForm.cycle} onChange={(value) => setCheckForm({ ...checkForm, cycle: value })} options={["รายวัน", "รายสัปดาห์", "รายเดือน", "ตามชั่วโมงใช้งาน", "ตามระยะทาง", "กำหนดเอง"]} />
              <Select label="ชื่ออุปกรณ์ / รหัสอุปกรณ์" value={checkForm.assetId} onChange={(value) => setCheckForm({ ...checkForm, assetId: value, beforeStatus: assetRows.find((item) => item.id === value)?.status || "" })} options={assetRows.map((item) => item.id)} />
              <Input label="ผู้ตรวจ" value={checkForm.inspector} onChange={(value) => setCheckForm({ ...checkForm, inspector: value })} />
              <Select label="สถานะก่อนตรวจ" value={checkForm.beforeStatus} onChange={(value) => setCheckForm({ ...checkForm, beforeStatus: value })} options={assetStatusOptions} />
              <Select label="ผลการตรวจ" value={checkForm.result} onChange={(value) => setCheckForm({ ...checkForm, result: value })} options={checkResultOptions} />
              <Textarea label="รายละเอียดปัญหา" value={checkForm.issue} onChange={(value) => setCheckForm({ ...checkForm, issue: value })} />
              <Textarea label="การแก้ไขเบื้องต้น" value={checkForm.fix} onChange={(value) => setCheckForm({ ...checkForm, fix: value })} />
              <Select label="ต้องแจ้งซ่อมหรือไม่" value={checkForm.repairRequired} onChange={(value) => setCheckForm({ ...checkForm, repairRequired: value })} options={["ไม่ต้องแจ้งซ่อม", "ต้องแจ้งซ่อม"]} />
              <Input label="ผู้รับผิดชอบติดตาม" value={checkForm.followOwner} onChange={(value) => setCheckForm({ ...checkForm, followOwner: value })} />
              <Input label="วันที่ต้องตรวจซ้ำ" value={checkForm.repeatDate} onChange={(value) => setCheckForm({ ...checkForm, repeatDate: value })} />
              <Input label="แนบรูปก่อนตรวจ" value={checkForm.beforePhoto} onChange={(value) => setCheckForm({ ...checkForm, beforePhoto: value })} />
              <Input label="แนบรูประหว่างตรวจ" value={checkForm.duringPhoto} onChange={(value) => setCheckForm({ ...checkForm, duringPhoto: value })} />
              <Input label="แนบรูปหลังตรวจ" value={checkForm.afterPhoto} onChange={(value) => setCheckForm({ ...checkForm, afterPhoto: value })} />
              <Textarea label="หมายเหตุ" value={checkForm.note} onChange={(value) => setCheckForm({ ...checkForm, note: value })} />
            </div>
            <button onClick={saveCheck} className="mt-5 w-full rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-soft">บันทึกการตรวจเช็ค</button>
          </div>
          <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
            <div className="flex items-start justify-between gap-3">
              <div><p className="text-xs font-extrabold text-goodseed-600">{selectedAsset?.id}</p><h3 className="text-xl font-extrabold text-goodseed-950">{selectedAsset?.name}</h3><p className="mt-1 text-sm font-semibold text-goodseed-700">{selectedAsset?.category} / {selectedAsset?.checkCycle}</p></div>
              <AssetStatusBadge status={selectedAsset?.status} />
            </div>
            <h4 className="mt-5 font-extrabold text-goodseed-900">Checklist การตรวจ {checklistType === "vehicle" ? "รถยนต์ / รถกระบะ" : checklistType === "engine" ? "เครื่องยนต์ / เครื่องจักร" : "อุปกรณ์เกษตรทั่วไป"}</h4>
            <div className="mt-4 grid gap-3 md:grid-cols-2">
              {currentChecklist.map((item) => (
                <label key={item} className={`flex cursor-pointer items-center gap-3 rounded-lg border p-3 text-sm font-bold transition ${checkedItems.includes(item) ? "border-goodseed-200 bg-goodseed-50 text-goodseed-900" : "border-slate-100 bg-white text-slate-600"}`}>
                  <input type="checkbox" checked={checkedItems.includes(item)} onChange={() => setCheckedItems((items) => items.includes(item) ? items.filter((value) => value !== item) : [...items, item])} className="h-4 w-4 accent-goodseed-700" />
                  {item}
                </label>
              ))}
            </div>
            <div className="mt-5 rounded-xl bg-goodseed-50 p-4">
              <p className="font-extrabold text-goodseed-900">ระบบแนบรูปถ่ายหลักฐาน</p>
              <div className="mt-3 grid gap-2 text-sm font-semibold text-goodseed-700 sm:grid-cols-2">
                {["รูปอุปกรณ์โดยรวม", "รูปจุดที่ตรวจ", "รูปความเสียหาย", "รูปเลขไมล์ / ชั่วโมงเครื่อง", "รูประดับน้ำมันเครื่อง", "รูปอะไหล่ที่เปลี่ยน", "รูปหลังทำความสะอาด", "รูปใบเสร็จซ่อม"].map((item) => <span key={item} className="rounded-lg bg-white p-2"><Icon name="camera" className="mr-2 inline h-4 w-4" />{item}</span>)}
              </div>
            </div>
          </div>
        </div>
      )}

      {activePanel === "history" && (
        <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
          <h3 className="text-xl font-extrabold text-goodseed-950">ประวัติการตรวจเช็ค</h3>
          <div className="mt-4 overflow-x-auto rounded-xl border border-goodseed-100">
            <table className="min-w-[980px] w-full text-left text-sm">
              <thead className="bg-goodseed-50 text-goodseed-800"><tr>{["วันที่ตรวจ", "รอบตรวจ", "ชื่ออุปกรณ์", "ผู้ตรวจ", "ผลการตรวจ", "รายละเอียดปัญหา", "รูปหลักฐาน"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr></thead>
              <tbody className="divide-y divide-goodseed-100">{checkRows.map((item) => <tr key={item.id}><td className="px-3 py-3">{item.date}</td><td className="px-3 py-3">{item.cycle}</td><td className="px-3 py-3 font-extrabold text-goodseed-950">{item.asset}</td><td className="px-3 py-3">{item.inspector}</td><td className="px-3 py-3"><Badge className={item.result === "ปกติ" ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : "bg-amber-100 text-amber-800 ring-amber-200"}>{item.result}</Badge></td><td className="px-3 py-3">{item.issue}</td><td className="px-3 py-3"><Icon name="camera" className="mr-2 inline h-4 w-4" />{item.evidence}</td></tr>)}</tbody>
            </table>
          </div>
        </div>
      )}

      {activePanel === "repair" && (
        <div className="grid gap-5 xl:grid-cols-[0.85fr_1.15fr]">
          <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
            <h3 className="text-xl font-extrabold text-goodseed-950">แจ้งซ่อม / บำรุงรักษา</h3>
            <div className="mt-5 grid gap-4">
              <Select label="ชื่ออุปกรณ์" value={repairForm.assetId} onChange={(value) => setRepairForm({ ...repairForm, assetId: value })} options={assetRows.map((item) => item.id)} />
              <Select label="ระดับความสำคัญ" value={repairForm.priority} onChange={(value) => setRepairForm({ ...repairForm, priority: value })} options={["ปานกลาง", "สำคัญ", "เร่งด่วน"]} />
              <Input label="ผู้รับผิดชอบติดตาม" value={repairForm.owner} onChange={(value) => setRepairForm({ ...repairForm, owner: value })} />
              <Input label="วันที่ต้องติดตาม" value={repairForm.due} onChange={(value) => setRepairForm({ ...repairForm, due: value })} />
              <Input label="แนบรูปความเสียหาย" value={repairForm.photo} onChange={(value) => setRepairForm({ ...repairForm, photo: value })} />
              <Input label="แนบใบเสร็จ / ใบเสนอราคา" value={repairForm.receipt} onChange={(value) => setRepairForm({ ...repairForm, receipt: value })} />
              <Textarea label="รายละเอียดการแจ้งซ่อม" value={repairForm.note} onChange={(value) => setRepairForm({ ...repairForm, note: value })} />
            </div>
            <button onClick={saveRepair} className="mt-5 w-full rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-soft">ส่งรายการแจ้งซ่อม</button>
          </div>
          <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
            <h3 className="text-xl font-extrabold text-goodseed-950">รายการซ่อมที่ต้องติดตาม</h3>
            <div className="mt-4 space-y-3">
              {repairRows.map((item) => (
                <div key={item.id} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4">
                  <div className="flex items-start justify-between gap-3"><div><p className="text-xs font-extrabold text-goodseed-600">{item.id}</p><p className="font-extrabold text-goodseed-950">{item.asset}</p></div><Badge className={item.priority === "เร่งด่วน" ? "bg-red-100 text-red-700 ring-red-200" : "bg-amber-100 text-amber-800 ring-amber-200"}>{item.priority}</Badge></div>
                  <p className="mt-2 text-sm font-semibold text-goodseed-700">{item.note}</p>
                  <div className="mt-3 grid gap-2 text-xs font-bold text-goodseed-700 sm:grid-cols-3"><span className="rounded-lg bg-white p-2">สถานะ: {item.status}</span><span className="rounded-lg bg-white p-2">ผู้ติดตาม: {item.owner}</span><span className="rounded-lg bg-white p-2">กำหนด: {item.due}</span></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {activePanel === "evidence" && (
        <div className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-soft">
          <h3 className="text-xl font-extrabold text-goodseed-950">เอกสารและรูปถ่ายหลักฐาน</h3>
          <p className="mt-2 text-sm font-semibold text-goodseed-700">รองรับรูปอุปกรณ์ ใบเสร็จ คู่มือ เอกสารรถ รูปเลขไมล์ รูปความเสียหาย รูปอะไหล่ที่เปลี่ยน และรูปหลังทำความสะอาด</p>
          <div className="mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            {[
              ["รูปอุปกรณ์โดยรวม", "ใช้ในทะเบียนหลักและตรวจเช็ค"],
              ["ใบเสร็จ / ใบเสนอราคา", "ใช้ประกอบการอนุมัติซ่อม"],
              ["คู่มือการใช้งาน", "แนบกับเครื่องจักรและรถยนต์"],
              ["เอกสารรถ", "พ.ร.บ. ประกันภัย ภาษี ตรวจสภาพ"],
              ["รูปเลขไมล์ / ชั่วโมงเครื่อง", "ใช้ติดตาม PM ตามระยะทางหรือชั่วโมง"],
              ["รูปจุดเสียหาย", "ใช้เปิดรายการแจ้งซ่อม"],
              ["รูปอะไหล่ที่เปลี่ยน", "ใช้เก็บประวัติซ่อมบำรุง"],
              ["รูปหลังทำความสะอาด", "ใช้ตรวจคุณภาพหลังใช้งาน"],
            ].map(([title, desc]) => <div key={title} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4"><Icon name="camera" className="h-6 w-6 text-goodseed-700" /><p className="mt-3 font-extrabold text-goodseed-950">{title}</p><p className="mt-1 text-sm font-semibold text-goodseed-700">{desc}</p><button className="mt-4 rounded-lg bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">แนบรูป / เอกสาร</button></div>)}
          </div>
        </div>
      )}
      </div>
    </section>
  );
}

const expenseRows = [
  { id: "EXP-001", type: "OPEX", layer: "COGS", category: "ต้นกล้า", item: "ค่าต้นกล้ารอบปลูก A", budget: 85000, actual: 82000, linkTo: "รอบปลูก A", evidence: "ใบเสร็จต้นกล้า 3 ไฟล์", recorder: "คุณหวาน", date: "25 พ.ค. 2569", note: "ต้นทุนตรงต่อการผลิตไม้ล้อม", status: "ปกติ" },
  { id: "EXP-002", type: "OPEX", layer: "COGS", category: "พันธุ์ / เมล็ดพันธุ์", item: "เมล็ดพันธุ์ถั่วบราซิล", budget: 22000, actual: 24500, linkTo: "สินค้า: ถั่วบราซิล", evidence: "รูปถ่ายถุงเมล็ดพันธุ์", recorder: "คุณหวาน", date: "24 พ.ค. 2569", note: "ใช้คำนวณต้นทุนต่อสินค้า", status: "ใกล้เกินงบ" },
  { id: "EXP-003", type: "OPEX", layer: "COGS", category: "ปุ๋ย", item: "ปุ๋ยชีวภาพและสารชีวภัณฑ์", budget: 60000, actual: 62500, linkTo: "รอบปลูก B", evidence: "ใบเบิกวัสดุ + ภาพสต็อก", recorder: "พี่ไกร", date: "23 พ.ค. 2569", note: "เกี่ยวข้องโดยตรงกับการผลิต", status: "เกินงบ" },
  { id: "EXP-004", type: "OPEX", layer: "COGS", category: "วัสดุปลูก", item: "ดินปลูก แกลบดำ วัสดุคลุมดิน", budget: 74000, actual: 71200, linkTo: "แปลง A1-A36", evidence: "Google Form เบิกวัสดุ", recorder: "พี่สมชาย", date: "23 พ.ค. 2569", note: "กระจายต้นทุนต่อแปลง", status: "ปกติ" },
  { id: "EXP-005", type: "OPEX", layer: "COGS", category: "ไบโอชา", item: "ไบโอชาใช้ปรับปรุงดิน", budget: 38000, actual: 35000, linkTo: "สินค้า: ไม้ล้อม", evidence: "ภาพก่อน-หลังใส่วัสดุ", recorder: "คุณหวาน", date: "22 พ.ค. 2569", note: "ต้นทุนต่อรอบปลูก C", status: "ปกติ" },
  { id: "EXP-006", type: "OPEX", layer: "COGS", category: "น้ำส้มควันไม้", item: "น้ำส้มควันไม้ป้องกันแมลง", budget: 18000, actual: 16500, linkTo: "แปลง B1", evidence: "รูปถ่ายการใช้งาน", recorder: "พี่ไกร", date: "21 พ.ค. 2569", note: "ใช้ในแปลงผลิต", status: "ปกติ" },
  { id: "EXP-007", type: "OPEX", layer: "COGS", category: "ค่าแรง", item: "ค่าแรงปลูกและดูแลแปลง", budget: 120000, actual: 96500, linkTo: "รอบปลูก A/B/C", evidence: "ตารางงานรายวัน", recorder: "คุณหวาน", date: "25 พ.ค. 2569", note: "ค่าแรงตรงต่อการผลิต", status: "ปกติ" },
  { id: "EXP-008", type: "OPEX", layer: "COGS", category: "ค่าน้ำ / ค่าไฟผลิต", item: "ค่าน้ำและไฟระบบน้ำหยด", budget: 42000, actual: 40500, linkTo: "ระบบน้ำ Zone 1-5", evidence: "บิลค่าน้ำไฟ", recorder: "คุณหวาน", date: "20 พ.ค. 2569", note: "เฉพาะส่วนเกี่ยวข้องกับการผลิต", status: "ปกติ" },
  { id: "EXP-009", type: "OPEX", layer: "Non-COGS", category: "ซ่อมแซม", item: "ค่าซ่อมโรงเรือนเดิม", budget: 32000, actual: 28800, linkTo: "โรงเรือนเพาะชำ", evidence: "ใบแจ้งซ่อม", recorder: "คุณหวาน", date: "19 พ.ค. 2569", note: "ซ่อมของเดิม จัดเป็น OPEX", status: "ปกติ" },
  { id: "EXP-010", type: "OPEX", layer: "Non-COGS", category: "ซ่อมอุปกรณ์", item: "ซ่อมเครื่องตัดหญ้า", budget: 15000, actual: 17800, linkTo: "อุปกรณ์ EQ-01", evidence: "ใบเสร็จร้านซ่อม", recorder: "พี่ไกร", date: "18 พ.ค. 2569", note: "ซ่อมแซมของเดิม ไม่ใช่ CAPEX", status: "เกินงบ" },
  { id: "EXP-011", type: "OPEX", layer: "Non-COGS", category: "ระบบรายงาน", item: "อินเทอร์เน็ต / ระบบรายงาน", budget: 12000, actual: 9800, linkTo: "ระบบจัดการฟาร์ม", evidence: "ใบแจ้งหนี้รายเดือน", recorder: "คุณหวาน", date: "15 พ.ค. 2569", note: "ค่าใช้จ่ายบริหารทั่วไป", status: "ปกติ" },
  { id: "EXP-012", type: "OPEX", layer: "Non-COGS", category: "บริหารจัดการ", item: "ค่าแรงบริหารจัดการ", budget: 65000, actual: 62000, linkTo: "สำนักงานฟาร์ม", evidence: "สรุปค่าแรง", recorder: "คุณหวาน", date: "25 พ.ค. 2569", note: "ไม่รวมใน Unit Cost", status: "ปกติ" },
  { id: "CAP-001", type: "CAPEX", layer: "-", category: "โรงเรือน", item: "สร้างโรงเรือนใหม่", budget: 450000, actual: 420000, linkTo: "โปรเจกต์โรงเรือน 2", evidence: "สัญญาจ้าง + รูปหน้างาน", recorder: "เจ้าของฟาร์ม", date: "10 พ.ค. 2569", note: "สร้างสินทรัพย์ใหม่ จัดเป็น CAPEX", status: "ปกติ" },
  { id: "CAP-002", type: "CAPEX", layer: "-", category: "เครื่องมือ", item: "ซื้อเครื่องพ่นยาใหม่", budget: 58000, actual: 61500, linkTo: "อุปกรณ์ใหม่", evidence: "ใบเสนอราคา / ใบเสร็จ", recorder: "คุณหวาน", date: "12 พ.ค. 2569", note: "ซื้อสินทรัพย์ใหม่", status: "ใกล้เกินงบ" },
  { id: "CAP-003", type: "CAPEX", layer: "-", category: "ระบบน้ำ", item: "วางระบบน้ำใหม่ Zone 6", budget: 180000, actual: 172000, linkTo: "โปรเจกต์ขยาย D", evidence: "รูปถ่ายติดตั้งระบบน้ำ", recorder: "เจ้าของฟาร์ม", date: "14 พ.ค. 2569", note: "ขยายระบบใหม่ รองรับรอบปลูก D", status: "ปกติ" },
  { id: "CAP-004", type: "CAPEX", layer: "-", category: "ถนนในฟาร์ม", item: "ทำถนนในฟาร์ม", budget: 260000, actual: 252000, linkTo: "โซนขยาย D-F", evidence: "รูปถ่ายหน้างาน", recorder: "เจ้าของฟาร์ม", date: "16 พ.ค. 2569", note: "เพิ่มสินทรัพย์ระยะยาว", status: "ปกติ" },
];

const revenueRows = [
  ["ขายไม้ล้อม", 620000, 18, "ลูกค้าหน้าฟาร์ม", "รับเงินแล้ว"],
  ["ต้นกล้า / กิ่งพันธุ์", 180000, 42, "LINE / หน้าฟาร์ม", "รับเงินแล้ว"],
  ["เมล็ดพันธุ์", 56000, 24, "ออนไลน์", "รอรับเงิน"],
  ["ไบโอชา", 245000, 31, "ตัวแทนจำหน่าย", "รับเงินบางส่วน"],
  ["น้ำส้มควันไม้", 164000, 27, "Shopee / หน้าฟาร์ม", "รับเงินแล้ว"],
  ["ดินปลูก / ปุ๋ยหมัก", 138000, 35, "เกษตรกรในพื้นที่", "รับเงินแล้ว"],
  ["สินค้าเกษตรอื่น ๆ", 92000, 16, "งานออกบูธ", "รับเงินแล้ว"],
];

const financeBudgetCategories = [
  "ค่าแรงประจำ",
  "ค่าแรงเฉพาะกิจ",
  "ค่าซื้ออุปกรณ์",
  "ค่าวัสดุปลูก",
  "ค่าปุ๋ย / ธาตุอาหาร",
  "ค่าน้ำมัน / เชื้อเพลิง",
  "ค่าซ่อมบำรุง",
  "ค่าเครื่องมือเกษตร",
  "ค่าระบบน้ำ",
  "ค่า R&D / ทดลองปลูก",
  "ค่าเดินทาง",
  "ค่าอาหาร / สวัสดิการ",
  "ค่าใช้จ่ายฉุกเฉิน",
  "อื่น ๆ ระบุเอง",
];

const initialCentralBudgets = [
  {
    id: "BUD-Y-2569",
    level: "รายปี",
    fiscalYear: "2569",
    month: "ทั้งปี",
    week: "-",
    amount: 4200000,
    owner: "คุณหวาน",
    purpose: "งบกองกลางสำหรับบริหารงานฟาร์มไม้ล้อม รอบปลูก A-F",
    category: "งบรวมทุกหมวด",
    categoryLimit: 4200000,
    start: "1 ม.ค. 2569",
    end: "31 ธ.ค. 2569",
    note: "Owner กำหนดวงเงินหลักประจำปี",
  },
  {
    id: "BUD-M-05-2569",
    level: "รายเดือน",
    fiscalYear: "2569",
    month: "พฤษภาคม",
    week: "-",
    amount: 520000,
    owner: "คุณหวาน",
    purpose: "ค่าแรง วัสดุปลูก ซ่อมบำรุง และค่าใช้จ่ายหน้างานเดือน พ.ค.",
    category: "ค่าแรงประจำ / ค่าวัสดุปลูก / ค่าซ่อมบำรุง",
    categoryLimit: 520000,
    start: "1 พ.ค. 2569",
    end: "31 พ.ค. 2569",
    note: "ใช้เป็นงบปฏิบัติการประจำเดือน",
  },
  {
    id: "BUD-W-04-05-2569",
    level: "รายสัปดาห์",
    fiscalYear: "2569",
    month: "พฤษภาคม",
    week: "สัปดาห์ที่ 4",
    amount: 125000,
    owner: "คุณหวาน",
    purpose: "งบงานตรวจแปลง ระบบน้ำ วัสดุปลูก และ R&D มันญี่ปุ่น",
    category: "ค่า R&D / ทดลองปลูก / ค่าระบบน้ำ / ค่าแรงเฉพาะกิจ",
    categoryLimit: 125000,
    start: "23 พ.ค. 2569",
    end: "29 พ.ค. 2569",
    note: "ถ้าใช้เกิน 90% ต้องแจ้ง Owner",
  },
];

const initialFundExpenses = [
  { id: "PAY-001", date: "23 พ.ค. 2569", type: "เบิกจ่าย", budgetLevel: "รายสัปดาห์", category: "ค่าปุ๋ย / ธาตุอาหาร", item: "ปุ๋ยชีวภาพและธาตุอาหารรอบปลูก A", reason: "ใช้บำรุงต้นไม้แปลง A1-A12 ตามแผนรายสัปดาห์", amount: 18500, payer: "คุณหวาน", receiver: "ร้านเกษตรโคกเจริญ", approver: "Owner", work: "ใส่ปุ๋ยรอบโคนต้น", plot: "แปลง A1-A12", plan: "Weekly Plan W4", evidence: "ใบเสร็จ + รูปวัสดุ", note: "หลักฐานครบ", status: "อนุมัติแล้ว" },
  { id: "PAY-002", date: "24 พ.ค. 2569", type: "สำรองจ่าย", budgetLevel: "รายเดือน", category: "ค่าซ่อมบำรุง", item: "ซ่อมปั๊มน้ำ Zone 2", reason: "แรงดันน้ำตก ส่งผลต่อการรดน้ำไม้ล้อม", amount: 12500, payer: "พี่ไกร", receiver: "ร้านซ่อมเครื่องสูบน้ำ", approver: "คุณหวาน", work: "ซ่อมระบบน้ำ", plot: "Zone 2", plan: "Monthly Maintenance", evidence: "รูปก่อนซ่อม / ใบเสนอราคา", note: "รอใบเสร็จฉบับจริง", status: "ต้องแนบหลักฐานเพิ่ม" },
  { id: "PAY-003", date: "25 พ.ค. 2569", type: "เบิกจ่าย", budgetLevel: "รายสัปดาห์", category: "ค่าแรงเฉพาะกิจ", item: "แรงงานถอนหญ้าและจัดแนวแปลง", reason: "เร่งจัดพื้นที่ก่อนตรวจแปลงประจำสัปดาห์", amount: 28800, payer: "คุณหวาน", receiver: "ทีมคนงานรายวัน", approver: "Owner", work: "ถอนหญ้า / จัดพื้นที่", plot: "แปลง B1-B24", plan: "Weekly Plan W4", evidence: "ตารางลงเวลา + รูปหน้างาน", note: "งานเสร็จตามแผน", status: "จ่ายแล้ว" },
  { id: "PAY-004", date: "26 พ.ค. 2569", type: "คืนเงิน", budgetLevel: "รายสัปดาห์", category: "ค่าน้ำมัน / เชื้อเพลิง", item: "คืนเงินค่าน้ำมันรถขนวัสดุ", reason: "เหลือจากวงเงินที่เบิกไว้สำหรับรับวัสดุ", amount: 3200, payer: "พี่สมชาย", receiver: "กองกลางฟาร์ม", approver: "คุณหวาน", work: "รับวัสดุจากร้านค้า", plot: "คลังวัสดุ", plan: "Inventory Refill", evidence: "บันทึกคืนเงิน", note: "คืนครบแล้ว", status: "คืนเงินแล้ว" },
  { id: "PAY-005", date: "27 พ.ค. 2569", type: "เบิกจ่าย", budgetLevel: "รายเดือน", category: "ค่า R&D / ทดลองปลูก", item: "วัสดุทดลองปลูกมันญี่ปุ่น", reason: "ใช้ทดลอง 4 สายพันธุ์ 4 รูปแบบ และเก็บข้อมูล R&D", amount: 46200, payer: "คุณหวาน", receiver: "ร้านวัสดุปลูก", approver: "Owner", work: "R&D ทดลองมันญี่ปุ่น", plot: "แปลงทดลอง GS-03", plan: "R&D Plan May", evidence: "ใบเสร็จ + รูปวัสดุ + Google Form", note: "ต้องติดตามผลสัปดาห์หน้า", status: "รออนุมัติ" },
  { id: "PAY-006", date: "27 พ.ค. 2569", type: "เบิกจ่าย", budgetLevel: "รายสัปดาห์", category: "ค่าใช้จ่ายฉุกเฉิน", item: "อะไหล่วาล์วน้ำเร่งด่วน", reason: "ระบบน้ำ Zone 4 รั่ว ต้องเปลี่ยนอะไหล่ทันที", amount: 9800, payer: "พี่ไกร", receiver: "ร้านระบบน้ำ", approver: "รอ Owner", work: "แก้ปัญหาระบบน้ำ", plot: "Zone 4", plan: "Emergency Repair", evidence: "รูปจุดรั่ว", note: "เกินงบหมวดย่อย ต้องขออนุมัติ", status: "เกินงบประมาณ" },
];

function FinanceDashboard({ role }) {
  const [period, setPeriod] = useState("รายเดือน");
  const [month, setMonth] = useState("พฤษภาคม");
  const [year, setYear] = useState("2569");
  const [accountFilter, setAccountFilter] = useState("ทั้งหมด");
  const [mainType, setMainType] = useState("OPEX");
  const [opexLayer, setOpexLayer] = useState("COGS");
  const [category, setCategory] = useState("ปุ๋ย");
  const [expenseDetailGroup, setExpenseDetailGroup] = useState(null);
  const [importModal, setImportModal] = useState(null);
  const [importStats, setImportStats] = useState({});
  const [centralBudgets, setCentralBudgets] = useState(initialCentralBudgets);
  const [fundExpenses, setFundExpenses] = useState(initialFundExpenses);
  const [budgetFilter, setBudgetFilter] = useState("ทั้งหมด");
  const [expenseStatusFilter, setExpenseStatusFilter] = useState("ทั้งหมด");
  const [financeNotice, setFinanceNotice] = useState("");
  const [budgetForm, setBudgetForm] = useState({
    level: "รายเดือน",
    fiscalYear: "2569",
    month: "พฤษภาคม",
    week: "สัปดาห์ที่ 4",
    amount: "125000",
    owner: "คุณหวาน",
    purpose: "งบกองกลางสำหรับงานฟาร์มประจำสัปดาห์",
    category: "ค่าวัสดุปลูก",
    categoryLimit: "45000",
    start: "23 พ.ค. 2569",
    end: "29 พ.ค. 2569",
    note: "",
  });
  const [expenseForm, setExpenseForm] = useState({
    date: "28 พ.ค. 2569",
    type: "เบิกจ่าย",
    budgetLevel: "รายสัปดาห์",
    category: "ค่าวัสดุปลูก",
    item: "วัสดุคลุมดินและแกลบดำ",
    reason: "ใช้ปรับปรุงแปลงไม้ล้อมตามแผนงานรายสัปดาห์",
    amount: "3500",
    payer: "คุณหวาน",
    receiver: "ร้านวัสดุเกษตร",
    approver: "Owner",
    work: "ปรับปรุงดินและคลุมโคนต้น",
    plot: "แปลง A1-A12",
    plan: "Weekly Plan W4",
    receipt: "receipt-photo.jpg",
    purchasePhoto: "material-photo.jpg",
    workPhoto: "work-evidence.jpg",
    note: "",
  });
  const opexItems = expenseRows.filter((row) => row.type === "OPEX");
  const cogsItems = expenseRows.filter((row) => row.type === "OPEX" && row.layer === "COGS");
  const capexItems = expenseRows.filter((row) => row.type === "CAPEX");
  const totalOpex = opexItems.reduce((sum, row) => sum + row.actual, 0);
  const totalCogs = cogsItems.reduce((sum, row) => sum + row.actual, 0);
  const totalCapex = capexItems.reduce((sum, row) => sum + row.actual, 0);
  const getImportAmount = (key) => (importStats[key]?.amount || 0);
  const getImportCount = (key) => (importStats[key]?.count || 0);
  const adjustedOpex = totalOpex + getImportAmount("OPEX") + getImportAmount("COGS");
  const adjustedCogs = totalCogs + getImportAmount("COGS");
  const adjustedCapex = totalCapex + getImportAmount("CAPEX");
  const totalRevenue = revenueRows.reduce((sum, row) => sum + row[1], 0) + getImportAmount("Revenue");
  const profit = totalRevenue - adjustedOpex;
  const margin = Math.round((profit / totalRevenue) * 100);
  const isOwner = isOwnerRole(role);
  const isAdmin = ["admin", "manager"].includes(role);
  const isStaff = role === "staff";
  const isCustomer = role === "customer";
  const canManageBudget = isOwner;
  const canRecordExpense = ["owner", "admin", "manager", "staff"].includes(role);
  const canApproveExpense = isOwner;
  const canSeeFinanceDetails = isOwner || isAdmin;
  const visibleMainType = isOwner ? mainType : "OPEX";
  const yearlyBudget = centralBudgets.find((budget) => budget.level === "รายปี") || centralBudgets[0];
  const monthlyBudget = centralBudgets.find((budget) => budget.level === "รายเดือน") || centralBudgets[1];
  const weeklyBudget = centralBudgets.find((budget) => budget.level === "รายสัปดาห์") || centralBudgets[2];
  const budgetUsedByLevel = (level) => fundExpenses
    .filter((row) => row.budgetLevel === level && row.type !== "คืนเงิน")
    .reduce((sum, row) => sum + row.amount, 0);
  const fundSpent = fundExpenses.filter((row) => row.type !== "คืนเงิน").reduce((sum, row) => sum + row.amount, 0);
  const fundReturned = fundExpenses.filter((row) => row.type === "คืนเงิน").reduce((sum, row) => sum + row.amount, 0);
  const fundBudgetBase = yearlyBudget?.amount || centralBudgets.reduce((sum, budget) => sum + budget.amount, 0);
  const remainingFund = Math.max(0, fundBudgetBase - fundSpent + fundReturned);
  const currentYearlyUsed = fundSpent;
  const currentMonthlyUsed = budgetUsedByLevel("รายเดือน");
  const currentWeeklyUsed = budgetUsedByLevel("รายสัปดาห์");
  const weeklyUsagePct = weeklyBudget ? Math.round((currentWeeklyUsed / weeklyBudget.amount) * 100) : 0;
  const pendingExpenses = fundExpenses.filter((row) => row.status === "รออนุมัติ").length;
  const missingEvidence = fundExpenses.filter((row) => row.status === "ต้องแนบหลักฐานเพิ่ม").length;
  const reservePaid = fundExpenses.filter((row) => row.type === "สำรองจ่าย").reduce((sum, row) => sum + row.amount, 0);
  const returnedMoney = fundReturned;
  const remainingBonusPool = Math.max(0, (weeklyBudget?.amount || 0) - currentWeeklyUsed);
  const performanceScore = 91;
  const bonusAllocation = Math.round(remainingBonusPool * 0.55);
  const welfareAllocation = Math.round(remainingBonusPool * 0.25);
  const visibleFundExpenses = fundExpenses.filter((row) => {
    const matchBudget = budgetFilter === "ทั้งหมด" || row.budgetLevel === budgetFilter;
    const matchStatus = expenseStatusFilter === "ทั้งหมด" || row.status === expenseStatusFilter;
    const matchRole = !isStaff || ["พี่ไกร", "พี่สมชาย", "คุณหวาน"].includes(row.payer);
    return matchBudget && matchStatus && matchRole;
  });
  const unitCost = [
    ["ต้นทุนต่อต้น", "Cost per Tree", adjustedCogs / 3354, "3,354 ต้นปัจจุบัน"],
    ["ต้นทุนต่อแปลง", "Cost per Plot", adjustedCogs / 3, "รอบปลูก A/B/C"],
    ["ต้นทุนต่อรอบปลูก", "Cost per Crop Cycle", adjustedCogs / 3, "3 รอบปลูก"],
    ["ต้นทุนต่อสินค้าไม้ล้อม", "Cost per Product", adjustedCogs / 3354, "สินค้าหลัก"],
  ];
  const confirmImport = (accountType, amount, count) => {
    setImportStats((current) => ({
      ...current,
      [accountType]: {
        amount: (current[accountType]?.amount || 0) + amount,
        count: (current[accountType]?.count || 0) + count,
      },
    }));
  };
  const expenseSummaries = [
    { key: "OPEX", th: "ค่าใช้จ่ายดำเนินงาน", en: "Operating Expenses", description: "ค่าใช้จ่ายประจำ การดูแล ซ่อมแซม และบริหารงานฟาร์ม", amount: adjustedOpex, rowCount: opexItems.length + getImportCount("OPEX") + getImportCount("COGS"), rows: opexItems, icon: "money", tone: "opex", status: "เกินงบ" },
    { key: "COGS", th: "ต้นทุนการผลิต", en: "Cost of Goods Sold", description: "ต้นทุนตรงที่ใช้คำนวณ Unit Cost ต่อไม้ล้อม แปลง และรอบปลูก", amount: adjustedCogs, rowCount: cogsItems.length + getImportCount("COGS"), rows: cogsItems, icon: "leaf", tone: "cogs", status: "เกินงบ" },
    { key: "CAPEX", th: "ค่าใช้จ่ายลงทุน", en: "Capital Expenditure", description: "ค่าใช้จ่ายสร้างใหม่ ซื้อสินทรัพย์ และขยายโครงสร้างระยะยาว", amount: adjustedCapex, rowCount: capexItems.length + getImportCount("CAPEX"), rows: capexItems, icon: "assets", tone: "capex", status: "ต้องตรวจสอบ" },
  ].filter((summary) => isOwner || (isAdmin && summary.key !== "CAPEX"));

  const saveBudget = () => {
    if (!canManageBudget) {
      setFinanceNotice("เฉพาะ Owner เท่านั้นที่ตั้งหรือแก้ไขวงเงินงบประมาณได้");
      return;
    }
    const amount = Number(budgetForm.amount || 0);
    const categoryLimit = Number(budgetForm.categoryLimit || amount || 0);
    if (!amount) {
      setFinanceNotice("กรุณาระบุวงเงินรวมก่อนบันทึกงบประมาณ");
      return;
    }
    const newBudget = {
      id: `BUD-${Date.now()}`,
      ...budgetForm,
      amount,
      categoryLimit,
    };
    setCentralBudgets((current) => [newBudget, ...current]);
    setFinanceNotice(`บันทึก${budgetForm.level}ใหม่ ${amount.toLocaleString("th-TH")} บาทแล้ว`);
  };

  const saveExpense = () => {
    if (!canRecordExpense) {
      setFinanceNotice("Role นี้ไม่มีสิทธิ์บันทึกรายจ่าย");
      return;
    }
    const amount = Number(expenseForm.amount || 0);
    if (!amount) {
      setFinanceNotice("กรุณาระบุจำนวนเงินก่อนบันทึกรายจ่าย");
      return;
    }
    const matchingBudget = centralBudgets.find((budget) => budget.level === expenseForm.budgetLevel);
    const used = budgetUsedByLevel(expenseForm.budgetLevel);
    if (!isOwner && matchingBudget && expenseForm.type !== "คืนเงิน" && used + amount > matchingBudget.amount) {
      setFinanceNotice("รายการนี้เกินวงเงินงบประมาณ ต้องกดขออนุมัติเพิ่มงบจาก Owner ก่อนบันทึก");
      return;
    }
    const newExpense = {
      id: `PAY-${Date.now()}`,
      date: expenseForm.date,
      type: expenseForm.type,
      budgetLevel: expenseForm.budgetLevel,
      category: expenseForm.category,
      item: expenseForm.item,
      reason: expenseForm.reason,
      amount,
      payer: expenseForm.payer,
      receiver: expenseForm.receiver,
      approver: expenseForm.approver,
      work: expenseForm.work,
      plot: expenseForm.plot,
      plan: expenseForm.plan,
      evidence: [expenseForm.receipt, expenseForm.purchasePhoto, expenseForm.workPhoto].filter(Boolean).join(" / ") || "รอแนบหลักฐาน",
      note: expenseForm.note || "-",
      status: isOwner ? "อนุมัติแล้ว" : "รออนุมัติ",
    };
    setFundExpenses((current) => [newExpense, ...current]);
    setFinanceNotice(`บันทึกรายจ่าย ${amount.toLocaleString("th-TH")} บาทแล้ว และอัปเดตยอดคงเหลือทันที`);
  };

  const requestExtraBudget = () => {
    setFinanceNotice("ส่งคำขออนุมัติเพิ่มงบให้ Owner แล้ว พร้อมเหตุผลและหลักฐานประกอบ");
  };

  if (isCustomer) {
    return (
      <section id="finance" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6 xl:col-span-3">
        <SectionHeader title={<BiLabel th="ผลประกอบการและค่าใช้จ่าย" en="Finance" />} subtitle="Customer/Public ไม่มีสิทธิ์เข้าถึงข้อมูลการเงินภายในฟาร์ม" />
        <div className="rounded-2xl bg-slate-50 p-5 text-sm font-bold text-slate-600">เมนูนี้ถูกซ่อนตาม Role-Based Access Control</div>
      </section>
    );
  }

  return (
    <section id="finance" className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6 xl:col-span-3">
      <SectionHeader
        title={<BiLabel th="ผลประกอบการและค่าใช้จ่าย" en="Financial Report: Revenue, Expenses & Profit" />}
        subtitle="ระบบงบกองกลาง บันทึกรายจ่าย ควบคุมวงเงิน แนบหลักฐาน และสรุปเงินคงเหลือเพื่อโบนัส / สวัสดิการ"
      />
      <CrudGovernanceBar role={role} moduleId="finance" title="Finance CRUD / Audit" />
      <FinancialTopActionBar
        period={period}
        setPeriod={setPeriod}
        month={month}
        setMonth={setMonth}
        year={year}
        setYear={setYear}
        accountFilter={accountFilter}
        setAccountFilter={setAccountFilter}
        onImport={() => setImportModal({ key: accountFilter === "ทั้งหมด" ? "OPEX" : accountFilter })}
        isOwner={isOwner}
      />
      {financeNotice && <div className="mb-5 rounded-2xl border border-goodseed-200 bg-goodseed-50 px-4 py-3 text-sm font-extrabold text-goodseed-900">{financeNotice}</div>}
      <CentralFundActionBar
        canManageBudget={canManageBudget}
        canRecordExpense={canRecordExpense}
        rows={visibleFundExpenses}
        onSaveBudget={saveBudget}
        onSaveExpense={saveExpense}
        onRequestExtra={requestExtraBudget}
      />
      <div className="grid gap-4 md:grid-cols-3 xl:grid-cols-5">
        <MiniMetric label={<BiLabel th="งบประมาณปีนี้" en="Annual Budget" />} value={`${(yearlyBudget?.amount || 0).toLocaleString("th-TH")} บาท`} />
        <MiniMetric label={<BiLabel th="งบประมาณเดือนนี้" en="Monthly Budget" />} value={`${(monthlyBudget?.amount || 0).toLocaleString("th-TH")} บาท`} />
        <MiniMetric label={<BiLabel th="งบประมาณสัปดาห์นี้" en="Weekly Budget" />} value={`${(weeklyBudget?.amount || 0).toLocaleString("th-TH")} บาท`} />
        <MiniMetric label={<BiLabel th="ใช้ไปแล้ว" en="Spent" />} value={`${fundSpent.toLocaleString("th-TH")} บาท`} danger={weeklyUsagePct >= 90} />
        <MiniMetric label={<BiLabel th="เงินคงเหลือ" en="Remaining Fund" />} value={`${remainingFund.toLocaleString("th-TH")} บาท`} />
        <MiniMetric label={<BiLabel th="รายจ่ายรออนุมัติ" en="Pending Approval" />} value={`${pendingExpenses} รายการ`} danger={pendingExpenses > 0} />
        <MiniMetric label={<BiLabel th="รายจ่ายไม่มีใบเสร็จ" en="Missing Evidence" />} value={`${missingEvidence} รายการ`} danger={missingEvidence > 0} />
        <MiniMetric label={<BiLabel th="เงินสำรองจ่าย" en="Advance Payment" />} value={`${reservePaid.toLocaleString("th-TH")} บาท`} />
        <MiniMetric label={<BiLabel th="เงินที่คืนแล้ว" en="Returned Money" />} value={`${returnedMoney.toLocaleString("th-TH")} บาท`} />
        <MiniMetric label={<BiLabel th="เงินเหลือเพื่อโบนัส / สวัสดิการ" en="Bonus / Welfare Pool" />} value={`${remainingBonusPool.toLocaleString("th-TH")} บาท`} />
      </div>
      <div className="mt-5 grid gap-4 xl:grid-cols-3">
        <BudgetLevelCard icon="calendar" budget={yearlyBudget} used={currentYearlyUsed} />
        <BudgetLevelCard icon="money" budget={monthlyBudget} used={currentMonthlyUsed} />
        <BudgetLevelCard icon="check" budget={weeklyBudget} used={currentWeeklyUsed} />
      </div>
      <div className="mt-5 grid gap-5 xl:grid-cols-[0.9fr_1.1fr]">
        <BudgetControlPanel
          weeklyBudget={weeklyBudget}
          currentWeeklyUsed={currentWeeklyUsed}
          weeklyUsagePct={weeklyUsagePct}
          pendingExpenses={pendingExpenses}
          missingEvidence={missingEvidence}
          onRequestExtra={requestExtraBudget}
        />
        <FinanceEvidenceCenter />
      </div>
      <div className="mt-5 grid gap-5 xl:grid-cols-2">
        <FinanceBudgetForm form={budgetForm} setForm={setBudgetForm} onSave={saveBudget} canManageBudget={canManageBudget} />
        <FundExpenseForm form={expenseForm} setForm={setExpenseForm} onSave={saveExpense} canRecordExpense={canRecordExpense} />
      </div>
      <div className="mt-5">
        <SpendingReportTable
          rows={visibleFundExpenses}
          budgetFilter={budgetFilter}
          setBudgetFilter={setBudgetFilter}
          expenseStatusFilter={expenseStatusFilter}
          setExpenseStatusFilter={setExpenseStatusFilter}
          canApproveExpense={canApproveExpense}
        />
      </div>
      <div className="mt-5">
        <BonusWelfarePanel
          startBudget={weeklyBudget?.amount || 0}
          spent={currentWeeklyUsed}
          remaining={remainingBonusPool}
          score={performanceScore}
          bonus={bonusAllocation}
          welfare={welfareAllocation}
        />
      </div>
      <div className="mt-6 border-t border-goodseed-100 pt-5">
        <SectionHeader
          title={<BiLabel th="สรุปบัญชี OPEX / COGS / CAPEX" en="Accounting Summary" />}
          subtitle={canSeeFinanceDetails ? "ส่วนนี้ใช้สำหรับวิเคราะห์บัญชีเชิงลึกและ Import Excel" : "Staff เห็นเฉพาะระบบบันทึกรายจ่ายและรายรับแบบสรุป ไม่เห็น OPEX / COGS / CAPEX แบบละเอียด"}
        />
      </div>
      <div className="grid gap-4 md:grid-cols-5">
        <MiniMetric label={<BiLabel th="รายรับรวม" en="Total Income / Revenue" />} value={totalRevenue.toLocaleString("th-TH")} />
        {canSeeFinanceDetails && <MiniMetric label={<BiLabel th="ค่าใช้จ่ายดำเนินงาน" en="Operating Expenses - OPEX" />} value={adjustedOpex.toLocaleString("th-TH")} danger />}
        {canSeeFinanceDetails && <MiniMetric label={<BiLabel th="ต้นทุนการผลิต" en="Cost of Goods Sold - COGS" />} value={adjustedCogs.toLocaleString("th-TH")} danger />}
        {isOwner && <MiniMetric label={<BiLabel th="ค่าใช้จ่ายลงทุน" en="Capital Expenditure - CAPEX" />} value={adjustedCapex.toLocaleString("th-TH")} />}
        <MiniMetric label={<BiLabel th="กำไรสุทธิ" en={isOwner ? `Net Profit / Margin ${margin}%` : "Net Profit detail hidden"} />} value={isOwner ? profit.toLocaleString("th-TH") : "จำกัดสิทธิ์"} />
      </div>
      {canSeeFinanceDetails && <div className="mt-5 grid gap-5 xl:grid-cols-[0.9fr_1.1fr]">
        <DashboardPanel title={<BiLabel th="แบบฟอร์มจัดประเภทค่าใช้จ่าย" en="Expense Classification Form" />}>
          <div className="grid gap-4 md:grid-cols-2">
            <Select label={<BiLabel th="ประเภทหลัก" en="Main Type" />} value={visibleMainType} onChange={setMainType} options={isOwner ? ["OPEX", "CAPEX"] : ["OPEX"]} />
            {visibleMainType === "OPEX" && <Select label={<BiLabel th="ชั้นย่อย OPEX" en="OPEX Layer" />} value={opexLayer} onChange={setOpexLayer} options={["COGS", "Non-COGS"]} />}
            <Select label={<BiLabel th="หมวดค่าใช้จ่าย" en="Expense Category" />} value={category} onChange={setCategory} options={["ต้นกล้า", "พันธุ์ / เมล็ดพันธุ์", "ปุ๋ย", "วัสดุปลูก", "ไบโอชา", "น้ำส้มควันไม้", "ค่าแรง", "ซ่อมแซม", "โรงเรือน", "ระบบน้ำ", "เครื่องมือ", "ถนนในฟาร์ม"]} />
            <Input label={<BiLabel th="ผูกกับรอบปลูก / แปลง / สินค้า / โปรเจกต์" en="Link to Crop Cycle / Plot / Product / Project" />} value={visibleMainType === "CAPEX" ? "โปรเจกต์ขยาย D-F" : "รอบปลูก A / แปลง A1-A36"} onChange={() => {}} />
            <Input label={<BiLabel th="แนบหลักฐาน / ใบเสร็จ / Google Form" en="Evidence / Receipt / Google Form Link" />} value="https://forms.gle/goodseed-expense-proof" onChange={() => {}} />
            <Input label={<BiLabel th="กติกาแยกประเภท" en="Classification Rule" />} value={visibleMainType === "CAPEX" ? "สร้างใหม่ / ซื้อสินทรัพย์ใหม่ = CAPEX" : opexLayer === "COGS" ? "ต้นทุนตรงการผลิต = COGS" : "บริหาร/ซ่อมของเดิม = Non-COGS"} onChange={() => {}} />
          </div>
        </DashboardPanel>
        {isOwner && <DashboardPanel title={<BiLabel th="ต้นทุนต่อหน่วยจาก COGS" en="Unit Cost from Cost of Goods Sold" />}>
          <div className="grid gap-3 sm:grid-cols-2">
            {unitCost.map(([label, en, value, note]) => <div key={label} className="rounded-lg bg-goodseed-50 p-4"><p className="text-xs font-extrabold text-goodseed-700"><BiLabel th={label} en={en} /></p><p className="mt-1 text-2xl font-extrabold text-goodseed-950">{Math.round(value).toLocaleString("th-TH")} บาท</p><p className="mt-1 text-xs font-bold text-goodseed-600">{note}</p></div>)}
          </div>
          <div className="mt-4 rounded-lg border border-goodseed-100 p-3 text-sm font-bold text-goodseed-800">สูตร (Formula): COGS รวม / จำนวนหน่วยผลิต เช่น ต้น, แปลง, รอบปลูก หรือสินค้า</div>
        </DashboardPanel>}
        {isAdmin && <DashboardPanel title={<BiLabel th="ข้อมูลที่ถูกจำกัดสิทธิ์" en="Restricted Financial Data" />}><div className="rounded-lg bg-amber-50 p-4 text-sm font-bold text-amber-800">Admin / Manager ไม่เห็นรายละเอียด CAPEX, Unit Cost และกำไรเชิงลึก</div></DashboardPanel>}
      </div>}
      {canSeeFinanceDetails && <div className="mt-5">
        <ExpenseSummaryCards summaries={expenseSummaries} period={period} selected={expenseDetailGroup} onOpen={setExpenseDetailGroup} onClose={() => setExpenseDetailGroup(null)} onImport={setImportModal} />
      </div>}
      <div className="mt-5">
        {canSeeFinanceDetails ? <RevenueTable rows={revenueRows} /> : <DashboardPanel title={<BiLabel th="รายรับแบบสรุป" en="Revenue Summary" />}><div className="rounded-2xl bg-goodseed-50 p-4"><p className="text-3xl font-extrabold text-goodseed-900">{totalRevenue.toLocaleString("th-TH")} บาท</p><p className="mt-2 text-sm font-bold text-goodseed-700">Staff เห็นเฉพาะภาพรวมรายรับและรายการค่าใช้จ่ายที่เกี่ยวข้องกับงานของตนเอง</p></div></DashboardPanel>}
      </div>
      {canSeeFinanceDetails && <div className="mt-5 grid gap-5 xl:grid-cols-[1fr_0.8fr]">
        <DashboardPanel title={<BiLabel th="รายรับเทียบค่าใช้จ่ายดำเนินงานรายเดือน" en="Monthly Revenue vs OPEX" />}><BarChart /></DashboardPanel>
        <DashboardPanel title={<BiLabel th="ต้นทุนแยกตามรอบปลูกและสินค้า" en="Cost by Crop Cycle & Product" />}><div className="space-y-3">{[["รอบปลูก A", 936], ["รอบปลูก B", 1196], ["รอบปลูก C", 1222], ["สินค้าไบโอชา", 245000], ["น้ำส้มควันไม้", 164000]].map(([label, amount]) => <div key={label} className="rounded-lg bg-goodseed-50 p-3"><div className="flex items-center justify-between gap-3"><p className="font-extrabold text-goodseed-900">{label}</p><p className="font-extrabold text-goodseed-700">{Math.round(adjustedCogs / (typeof amount === "number" && amount < 10000 ? amount : 1000)).toLocaleString("th-TH")} บาท/หน่วย <span className="text-xs text-goodseed-600">(THB/Unit)</span></p></div><div className="mt-2 h-2 rounded-full bg-white"><div className="h-full rounded-full bg-goodseed-600" style={{ width: `${Math.min(92, Math.round((Number(amount) / 3354) * 100))}%` }} /></div></div>)}</div></DashboardPanel>
      </div>}
      <ImportExcelModal open={Boolean(importModal)} initialType={importModal?.key || "OPEX"} onClose={() => setImportModal(null)} onConfirm={confirmImport} />
    </section>
  );
}

function BudgetHealthBadge({ pct = 0, status }) {
  const label = status || (pct >= 100 ? "เกินงบประมาณ" : pct >= 90 ? "ใช้เกิน 90%" : pct >= 70 ? "เฝ้าระวัง 70%" : "ปกติ");
  const className = pct >= 100 || status === "เกินงบประมาณ"
    ? "bg-red-100 text-red-700 ring-red-200"
    : pct >= 90
      ? "bg-red-50 text-red-700 ring-red-200"
      : pct >= 70
        ? "bg-amber-100 text-amber-800 ring-amber-200"
        : "bg-goodseed-100 text-goodseed-800 ring-goodseed-200";
  return <Badge className={className}>{label}</Badge>;
}

function BudgetProgressBar({ value = 0 }) {
  const safeValue = Math.min(100, Math.max(0, value));
  const color = safeValue >= 100 ? "bg-red-600" : safeValue >= 90 ? "bg-red-500" : safeValue >= 70 ? "bg-amber-500" : "bg-goodseed-600";
  return (
    <div className="h-3 overflow-hidden rounded-full bg-white ring-1 ring-goodseed-100">
      <div className={`h-full rounded-full ${color} transition-all duration-500`} style={{ width: `${safeValue}%` }} />
    </div>
  );
}

function ExpenseStatusBadge({ status }) {
  const tones = {
    "รออนุมัติ": "bg-amber-100 text-amber-800 ring-amber-200",
    "อนุมัติแล้ว": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
    "ไม่อนุมัติ": "bg-red-100 text-red-700 ring-red-200",
    "จ่ายแล้ว": "bg-blue-100 text-blue-700 ring-blue-200",
    "คืนเงินแล้ว": "bg-emerald-100 text-emerald-800 ring-emerald-200",
    "ต้องแนบหลักฐานเพิ่ม": "bg-orange-100 text-orange-800 ring-orange-200",
    "เกินงบประมาณ": "bg-red-100 text-red-700 ring-red-200",
  };
  return <Badge className={tones[status] || "bg-slate-100 text-slate-700 ring-slate-200"}>{status}</Badge>;
}

function CentralFundActionBar({ canManageBudget, canRecordExpense, rows, onSaveBudget, onSaveExpense, onRequestExtra }) {
  const csv = "\ufeffวันที่,ประเภท,หมวด,รายการ,จำนวนเงิน,ผู้จ่าย,ผู้อนุมัติ,สถานะ\n"
    + rows.map((row) => [row.date, row.type, row.category, row.item, row.amount, row.payer, row.approver, row.status].map((cell) => `"${String(cell).replaceAll('"', '""')}"`).join(",")).join("\n");
  return (
    <div className="mb-5 rounded-2xl border border-goodseed-100 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
        <div>
          <p className="text-sm font-extrabold text-goodseed-950">ระบบงบประมาณกองกลาง</p>
          <p className="mt-1 text-xs font-bold leading-5 text-goodseed-600">Owner ตั้งงบ ส่วน Manager/Staff บันทึกรายจ่ายและแนบหลักฐานตามสิทธิ์</p>
        </div>
        <div className="grid gap-2 sm:grid-cols-2 xl:flex xl:flex-wrap">
          <button type="button" onClick={onSaveBudget} className={`inline-flex items-center justify-center gap-2 rounded-xl px-4 py-3 text-sm font-extrabold shadow-sm transition ${canManageBudget ? "bg-goodseed-700 text-white hover:bg-goodseed-800" : "bg-slate-100 text-slate-500"}`}>
            <Icon name="money" className="h-4 w-4" />
            ตั้งงบใหม่
          </button>
          <button type="button" onClick={onSaveExpense} className={`inline-flex items-center justify-center gap-2 rounded-xl px-4 py-3 text-sm font-extrabold shadow-sm transition ${canRecordExpense ? "bg-white text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-50" : "bg-slate-100 text-slate-500"}`}>
            <Icon name="file" className="h-4 w-4" />
            บันทึกรายจ่าย
          </button>
          <button type="button" onClick={onRequestExtra} className="inline-flex items-center justify-center gap-2 rounded-xl bg-amber-100 px-4 py-3 text-sm font-extrabold text-amber-800 ring-1 ring-amber-200 transition hover:bg-amber-200">
            <Icon name="bell" className="h-4 w-4" />
            ขออนุมัติเพิ่มงบ
          </button>
          <a href="#finance-expense-form" className="inline-flex items-center justify-center gap-2 rounded-xl bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-50">
            <Icon name="camera" className="h-4 w-4" />
            แนบใบเสร็จ
          </a>
          <button type="button" onClick={() => downloadFile("goodseed-central-fund-report.csv", csv, "text/csv;charset=utf-8")} className="inline-flex items-center justify-center gap-2 rounded-xl bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-50">
            <Icon name="download" className="h-4 w-4" />
            สรุปรายงาน
          </button>
        </div>
      </div>
    </div>
  );
}

function BudgetLevelCard({ budget, used = 0, icon }) {
  if (!budget) return null;
  const remaining = Math.max(0, budget.amount - used);
  const pct = budget.amount ? Math.round((used / budget.amount) * 100) : 0;
  return (
    <div className="rounded-2xl border border-goodseed-100 bg-goodseed-50 p-5 shadow-sm">
      <div className="flex items-start justify-between gap-4">
        <div>
          <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{budget.level}</Badge>
          <h3 className="mt-3 text-xl font-extrabold text-goodseed-950">{budget.month} {budget.week !== "-" ? budget.week : ""}</h3>
          <p className="mt-1 text-sm font-bold leading-6 text-goodseed-700">{budget.purpose}</p>
        </div>
        <div className="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-white text-goodseed-800 shadow-sm">
          <Icon name={icon} className="h-6 w-6" />
        </div>
      </div>
      <div className="mt-5 grid gap-3 sm:grid-cols-3">
        <div className="rounded-xl bg-white p-3">
          <p className="text-[11px] font-bold text-goodseed-600">วงเงิน</p>
          <p className="mt-1 whitespace-nowrap text-lg font-extrabold text-goodseed-950">{budget.amount.toLocaleString("th-TH")} บาท</p>
        </div>
        <div className="rounded-xl bg-white p-3">
          <p className="text-[11px] font-bold text-goodseed-600">ใช้ไป</p>
          <p className="mt-1 whitespace-nowrap text-lg font-extrabold text-goodseed-950">{used.toLocaleString("th-TH")} บาท</p>
        </div>
        <div className="rounded-xl bg-white p-3">
          <p className="text-[11px] font-bold text-goodseed-600">คงเหลือ</p>
          <p className="mt-1 whitespace-nowrap text-lg font-extrabold text-goodseed-950">{remaining.toLocaleString("th-TH")} บาท</p>
        </div>
      </div>
      <div className="mt-4 space-y-3">
        <div className="flex items-center justify-between gap-3 text-sm">
          <span className="font-extrabold text-goodseed-900">การใช้งบ {pct}%</span>
          <BudgetHealthBadge pct={pct} />
        </div>
        <BudgetProgressBar value={pct} />
        <p className="text-xs font-bold leading-5 text-goodseed-600">{budget.start} - {budget.end} / ผู้รับผิดชอบ: {budget.owner}</p>
      </div>
    </div>
  );
}

function BudgetControlPanel({ weeklyBudget, currentWeeklyUsed, weeklyUsagePct, pendingExpenses, missingEvidence, onRequestExtra }) {
  const remaining = Math.max(0, (weeklyBudget?.amount || 0) - currentWeeklyUsed);
  return (
    <DashboardPanel title={<BiLabel th="ระบบควบคุมวงเงิน" en="Budget Control Rules" />}>
      <div className="rounded-2xl bg-goodseed-50 p-4">
        <div className="flex items-center justify-between gap-4">
          <div>
            <p className="text-sm font-extrabold text-goodseed-950">งบรายสัปดาห์ปัจจุบัน</p>
            <p className="mt-1 text-3xl font-extrabold text-goodseed-900">{(weeklyBudget?.amount || 0).toLocaleString("th-TH")} บาท</p>
          </div>
          <BudgetHealthBadge pct={weeklyUsagePct} />
        </div>
        <div className="mt-4">
          <BudgetProgressBar value={weeklyUsagePct} />
          <div className="mt-3 flex flex-wrap justify-between gap-3 text-sm font-bold text-goodseed-700">
            <span>ใช้แล้ว {currentWeeklyUsed.toLocaleString("th-TH")} บาท</span>
            <span>คงเหลือ {remaining.toLocaleString("th-TH")} บาท</span>
          </div>
        </div>
      </div>
      <div className="mt-4 grid gap-3 md:grid-cols-2">
        {[
          ["แจ้งเตือน 70%", "เมื่อใช้เกิน 70% ระบบเตือนให้ตรวจแผนใช้เงิน"],
          ["แจ้งเตือน 90%", "เมื่อใช้เกิน 90% ต้องแจ้ง Owner ก่อนใช้เพิ่ม"],
          ["ห้ามเกินวงเงิน", "Manager/Staff บันทึกเกินงบไม่ได้หาก Owner ยังไม่อนุมัติ"],
          ["หลักฐานต้องครบ", `${missingEvidence} รายการต้องแนบหลักฐานเพิ่ม / ${pendingExpenses} รายการรออนุมัติ`],
        ].map(([title, detail]) => (
          <div key={title} className="rounded-xl border border-goodseed-100 bg-white p-4">
            <p className="font-extrabold text-goodseed-950">{title}</p>
            <p className="mt-1 text-sm font-semibold leading-6 text-goodseed-700">{detail}</p>
          </div>
        ))}
      </div>
      <button type="button" onClick={onRequestExtra} className="mt-4 w-full rounded-xl bg-amber-100 px-4 py-3 text-sm font-extrabold text-amber-800 ring-1 ring-amber-200 transition hover:bg-amber-200">
        ขออนุมัติเพิ่มงบ
      </button>
    </DashboardPanel>
  );
}

function FinanceEvidenceCenter() {
  const evidenceItems = [
    ["ใบเสร็จ", "Receipt"],
    ["รูปของที่ซื้อ", "Purchase Photo"],
    ["รูปหลักฐานงาน", "Work Evidence"],
    ["Google Form / Drive", "Form Link"],
    ["ชื่อผู้บันทึก", "Recorder"],
    ["วันที่บันทึก", "Record Date"],
  ];
  return (
    <DashboardPanel title={<BiLabel th="เอกสารหลักฐานการเงิน" en="Financial Evidence Center" />}>
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {evidenceItems.map(([th, en]) => (
          <div key={th} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4">
            <Icon name="file" className="h-5 w-5 text-goodseed-700" />
            <p className="mt-3 text-sm font-extrabold text-goodseed-950">{th}</p>
            <p className="text-xs font-bold text-goodseed-600">{en}</p>
          </div>
        ))}
      </div>
      <div className="mt-4 rounded-2xl bg-white p-4 ring-1 ring-goodseed-100">
        <p className="text-sm font-extrabold text-goodseed-950">แนวทางตรวจสอบ</p>
        <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">ทุกการใช้เงินต้องมีเหตุผล รายละเอียด ผู้อนุมัติ และหลักฐานประกอบ เพื่อให้เงินกองกลางโปร่งใสและตรวจสอบย้อนหลังได้</p>
      </div>
    </DashboardPanel>
  );
}

function FinanceBudgetForm({ form, setForm, onSave, canManageBudget }) {
  const update = (key) => (value) => setForm((current) => ({ ...current, [key]: value }));
  return (
    <DashboardPanel id="finance-budget-form" title={<BiLabel th="ตั้งงบประมาณ" en="Budget Setup" />} action={<Badge className={canManageBudget ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : "bg-slate-100 text-slate-600 ring-slate-200"}>{canManageBudget ? "Owner Only" : "Read Only"}</Badge>}>
      {!canManageBudget && <p className="mb-4 rounded-xl bg-amber-50 p-3 text-sm font-bold text-amber-800">เฉพาะ Owner เท่านั้นที่กำหนดวงเงินงบประมาณได้</p>}
      <div className="grid gap-4 md:grid-cols-2">
        <Select label="ระดับงบประมาณ" value={form.level} onChange={update("level")} options={["รายปี", "รายเดือน", "รายสัปดาห์"]} />
        <Input label="ปีงบประมาณ" value={form.fiscalYear} onChange={update("fiscalYear")} />
        <Input label="เดือน" value={form.month} onChange={update("month")} />
        <Input label="สัปดาห์" value={form.week} onChange={update("week")} />
        <Input label="วงเงินรวม" type="number" value={form.amount} onChange={update("amount")} />
        <Input label="ผู้รับผิดชอบงบ" value={form.owner} onChange={update("owner")} />
        <Select label="หมวดค่าใช้จ่าย" value={form.category} onChange={update("category")} options={financeBudgetCategories} />
        <Input label="วงเงินต่อหมวด" type="number" value={form.categoryLimit} onChange={update("categoryLimit")} />
        <Input label="วันที่เริ่มใช้" value={form.start} onChange={update("start")} />
        <Input label="วันที่สิ้นสุดงบ" value={form.end} onChange={update("end")} />
        <Textarea label="วัตถุประสงค์ของงบ" value={form.purpose} onChange={update("purpose")} wide />
        <Textarea label="หมายเหตุ" value={form.note} onChange={update("note")} wide />
      </div>
      <button type="button" onClick={onSave} className={`mt-5 w-full rounded-xl px-5 py-3 text-sm font-extrabold shadow-sm transition ${canManageBudget ? "bg-goodseed-700 text-white hover:bg-goodseed-800" : "bg-slate-100 text-slate-500"}`}>
        บันทึกงบประมาณ
      </button>
    </DashboardPanel>
  );
}

function FundExpenseForm({ form, setForm, onSave, canRecordExpense }) {
  const update = (key) => (value) => setForm((current) => ({ ...current, [key]: value }));
  return (
    <DashboardPanel id="finance-expense-form" title={<BiLabel th="บันทึกรายจ่าย" en="Expense Entry" />} action={<Badge className={canRecordExpense ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : "bg-slate-100 text-slate-600 ring-slate-200"}>{canRecordExpense ? "Allowed" : "No Access"}</Badge>}>
      <div className="grid gap-4 md:grid-cols-2">
        <Input label="วันที่จ่าย" value={form.date} onChange={update("date")} />
        <Select label="ประเภทการจ่าย" value={form.type} onChange={update("type")} options={["เบิกจ่าย", "สำรองจ่าย", "คืนเงิน", "ปรับยอด"]} />
        <Select label="งบที่ใช้" value={form.budgetLevel} onChange={update("budgetLevel")} options={["รายปี", "รายเดือน", "รายสัปดาห์"]} />
        <Select label="หมวดค่าใช้จ่าย" value={form.category} onChange={update("category")} options={financeBudgetCategories} />
        <Input label="รายการที่ใช้จ่าย" value={form.item} onChange={update("item")} />
        <Input label="จำนวนเงิน" type="number" value={form.amount} onChange={update("amount")} />
        <Input label="ผู้จ่ายเงิน" value={form.payer} onChange={update("payer")} />
        <Input label="ผู้รับเงิน" value={form.receiver} onChange={update("receiver")} />
        <Input label="ผู้อนุมัติ" value={form.approver} onChange={update("approver")} />
        <Input label="ใช้กับงานอะไร" value={form.work} onChange={update("work")} />
        <Input label="ใช้กับแปลง / โซนไหน" value={form.plot} onChange={update("plot")} />
        <Input label="เกี่ยวข้องกับแผนงานใด" value={form.plan} onChange={update("plan")} />
        <Textarea label="รายละเอียดเหตุผลในการใช้เงิน" value={form.reason} onChange={update("reason")} wide />
        <UploadBox label="แนบรูปใบเสร็จ" value={form.receipt} onChange={update("receipt")} />
        <UploadBox label="แนบรูปของที่ซื้อ" value={form.purchasePhoto} onChange={update("purchasePhoto")} />
        <UploadBox label="แนบรูปหลักฐานงาน" value={form.workPhoto} onChange={update("workPhoto")} />
        <Textarea label="หมายเหตุ" value={form.note} onChange={update("note")} wide />
      </div>
      <button type="button" onClick={onSave} className={`mt-5 w-full rounded-xl px-5 py-3 text-sm font-extrabold shadow-sm transition ${canRecordExpense ? "bg-goodseed-700 text-white hover:bg-goodseed-800" : "bg-slate-100 text-slate-500"}`}>
        บันทึกรายการ
      </button>
    </DashboardPanel>
  );
}

function SpendingReportTable({ rows, budgetFilter, setBudgetFilter, expenseStatusFilter, setExpenseStatusFilter, canApproveExpense }) {
  const statuses = ["ทั้งหมด", "รออนุมัติ", "อนุมัติแล้ว", "ไม่อนุมัติ", "จ่ายแล้ว", "คืนเงินแล้ว", "ต้องแนบหลักฐานเพิ่ม", "เกินงบประมาณ"];
  return (
    <DashboardPanel
      title={<BiLabel th="รายงานการใช้เงิน" en="Spending Report" />}
      action={
        <div className="grid gap-2 sm:grid-cols-2">
          <Select label="งบ" value={budgetFilter} onChange={setBudgetFilter} options={["ทั้งหมด", "รายปี", "รายเดือน", "รายสัปดาห์"]} />
          <Select label="สถานะ" value={expenseStatusFilter} onChange={setExpenseStatusFilter} options={statuses} />
        </div>
      }
    >
      <div className="thin-scrollbar overflow-x-auto">
        <table className="min-w-[1180px] w-full text-left text-sm">
          <thead className="bg-goodseed-50 text-goodseed-800">
            <tr>
              {["วันที่", "รายการ", "หมวดค่าใช้จ่าย", "จำนวนเงิน", "ผู้ใช้เงิน", "ผู้อนุมัติ", "งานที่เกี่ยวข้อง", "สถานะ", "หลักฐาน", "หมายเหตุ"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}
            </tr>
          </thead>
          <tbody className="divide-y divide-goodseed-100">
            {rows.map((row) => (
              <tr key={row.id} className="align-top">
                <td className="px-3 py-3 font-bold text-goodseed-900">{row.date}</td>
                <td className="px-3 py-3"><p className="font-extrabold text-goodseed-950">{row.item}</p><p className="mt-1 text-xs font-semibold text-goodseed-600">{row.reason}</p></td>
                <td className="px-3 py-3 font-bold">{row.category}</td>
                <td className="px-3 py-3 whitespace-nowrap font-extrabold">{row.amount.toLocaleString("th-TH")} บาท</td>
                <td className="px-3 py-3">{row.payer}</td>
                <td className="px-3 py-3">{row.approver}</td>
                <td className="px-3 py-3"><p>{row.work}</p><p className="text-xs font-bold text-goodseed-600">{row.plot} / {row.plan}</p></td>
                <td className="px-3 py-3"><ExpenseStatusBadge status={row.status} />{canApproveExpense && row.status === "รออนุมัติ" && <button className="mt-2 block rounded-lg bg-goodseed-700 px-3 py-1.5 text-xs font-extrabold text-white">อนุมัติ</button>}</td>
                <td className="px-3 py-3 text-xs font-bold text-goodseed-700">{row.evidence}</td>
                <td className="px-3 py-3 text-slate-600">{row.note}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </DashboardPanel>
  );
}

function BonusWelfarePanel({ startBudget, spent, remaining, score, bonus, welfare }) {
  const remainingPct = startBudget ? Math.round((remaining / startBudget) * 100) : 0;
  return (
    <DashboardPanel title={<BiLabel th="เงินคงเหลือเพื่อโบนัสและสวัสดิการ" en="Remaining Fund for Bonus & Welfare" />}>
      <div className="grid gap-4 md:grid-cols-4">
        <MiniMetric label="งบประมาณตั้งต้น" value={`${startBudget.toLocaleString("th-TH")} บาท`} />
        <MiniMetric label="ยอดใช้จริง" value={`${spent.toLocaleString("th-TH")} บาท`} danger={spent > startBudget} />
        <MiniMetric label="เงินคงเหลือ" value={`${remaining.toLocaleString("th-TH")} บาท`} />
        <MiniMetric label="เปอร์เซ็นต์เงินเหลือ" value={`${remainingPct}%`} />
      </div>
      <div className="mt-4 grid gap-4 lg:grid-cols-[0.8fr_1.2fr]">
        <div className="rounded-2xl bg-goodseed-50 p-5">
          <p className="text-sm font-extrabold text-goodseed-950">คะแนนประสิทธิภาพงาน</p>
          <p className="mt-2 text-5xl font-extrabold text-goodseed-800">{score}</p>
          <p className="mt-2 text-sm font-bold text-goodseed-700">ประเมินจากงานสำเร็จตามแผน หลักฐานครบ และไม่เบิกเกินงบโดยไม่มีเหตุผล</p>
          <div className="mt-4 grid gap-3 sm:grid-cols-2">
            <div className="rounded-xl bg-white p-4">
              <p className="text-xs font-bold text-goodseed-600">จัดสรรเป็นโบนัส</p>
              <p className="mt-1 text-xl font-extrabold text-goodseed-950">{bonus.toLocaleString("th-TH")} บาท</p>
            </div>
            <div className="rounded-xl bg-white p-4">
              <p className="text-xs font-bold text-goodseed-600">จัดสรรเป็นสวัสดิการ</p>
              <p className="mt-1 text-xl font-extrabold text-goodseed-950">{welfare.toLocaleString("th-TH")} บาท</p>
            </div>
          </div>
        </div>
        <div className="rounded-2xl border border-goodseed-100 bg-white p-5">
          <p className="font-extrabold text-goodseed-950">เงื่อนไขการจ่ายโบนัส / สวัสดิการ</p>
          <div className="mt-3 grid gap-2">
            {[
              "งานสำเร็จตามแผนรายสัปดาห์ / รายเดือน",
              "ไม่มีรายจ่ายผิดวัตถุประสงค์",
              "มีหลักฐานครบถ้วน",
              "ไม่เบิกเกินงบโดยไม่มีเหตุผล",
              "อุปกรณ์และวัสดุที่ซื้อใช้จริงกับงานฟาร์ม",
              "เงินเหลือเกิดจากการบริหารดี ไม่ใช่การลดคุณภาพงาน",
            ].map((item) => (
              <div key={item} className="flex items-start gap-2 rounded-xl bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800">
                <Icon name="check" className="mt-0.5 h-4 w-4 shrink-0" />
                <span>{item}</span>
              </div>
            ))}
          </div>
          <p className="mt-4 rounded-xl bg-amber-50 p-3 text-sm font-bold text-amber-800">หมายเหตุจาก Owner: การจัดสรรจริงต้องตรวจคุณภาพงานและหลักฐานการใช้เงินก่อนทุกครั้ง</p>
        </div>
      </div>
    </DashboardPanel>
  );
}

function FinancialTopActionBar({ period, setPeriod, month, setMonth, year, setYear, accountFilter, setAccountFilter, onImport, isOwner }) {
  const exportRows = expenseRows.filter((row) => isOwner || row.type !== "CAPEX");
  return (
    <div className="my-5 rounded-2xl border border-goodseed-100 bg-goodseed-50/80 p-4 shadow-sm">
      <div className="grid gap-3 xl:grid-cols-[auto_1fr] xl:items-end">
        <div className="flex flex-wrap gap-2">
          <button data-testid="finance-import-excel-top" onClick={onImport} className="inline-flex items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-4 py-3 text-sm font-extrabold text-white shadow-sm transition hover:bg-goodseed-800">
            <Icon name="upload" className="h-4 w-4" />
            Import Excel
          </button>
          <button onClick={() => downloadFile("goodseed-financial-report.csv", "\ufeffประเภท,หมวด,รายการ,ยอดจริง\n" + exportRows.map((row) => `${row.type},${row.category},${row.item},${row.actual}`).join("\n"), "text/csv;charset=utf-8")} className="inline-flex items-center justify-center gap-2 rounded-xl border border-goodseed-200 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 shadow-sm transition hover:bg-goodseed-50">
            <Icon name="download" className="h-4 w-4" />
            Export Report
          </button>
          <a href="#finance" className="inline-flex items-center justify-center gap-2 rounded-xl border border-goodseed-200 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 shadow-sm transition hover:bg-goodseed-50">
            <Icon name="file" className="h-4 w-4" />
            Add Manual Entry
          </a>
        </div>
        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
          <Select label={<BiLabel th="ช่วงเวลา" en="Period" />} value={period} onChange={setPeriod} options={["รายเดือน", "รายไตรมาส", "รายปี"]} />
          <Select label={<BiLabel th="เดือน" en="Month" />} value={month} onChange={setMonth} options={["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"]} />
          <Select label={<BiLabel th="ปี" en="Year" />} value={year} onChange={setYear} options={["2569", "2570", "2571"]} />
          <Select label={<BiLabel th="หมวดบัญชี" en="Account Category" />} value={accountFilter} onChange={setAccountFilter} options={isOwner ? ["ทั้งหมด", "OPEX", "COGS", "CAPEX", "Revenue", "Payroll"] : ["ทั้งหมด", "OPEX", "COGS", "Revenue", "Payroll"]} />
        </div>
      </div>
    </div>
  );
}

function FinancialMetricBox({ label, value, unit, statusClass = "" }) {
  return (
    <div className="min-w-[140px] rounded-xl border border-white/70 bg-white/85 p-4 shadow-sm">
      <p className="min-h-[34px] text-xs font-extrabold leading-5 text-goodseed-600">{label}</p>
      <div className="mt-2 flex min-h-[38px] items-center gap-2">
        <p className={`whitespace-nowrap text-2xl font-extrabold leading-none text-goodseed-950 ${statusClass}`}>{value}</p>
        {unit && <span className="whitespace-nowrap text-xs font-extrabold text-goodseed-500">{unit}</span>}
      </div>
    </div>
  );
}

function ImportExcelModal({ open, initialType, onClose, onConfirm }) {
  const [accountType, setAccountType] = useState(initialType);
  const [fileName, setFileName] = useState("");
  const [sheetName, setSheetName] = useState("Sheet 1");
  const [imported, setImported] = useState(false);
  useEffect(() => {
    if (open) {
      setAccountType(initialType);
      setFileName("");
      setSheetName("Sheet 1");
      setImported(false);
    }
  }, [open, initialType]);
  const previewRows = [
    ["25/05/2569", accountType, "ปุ๋ยชีวภาพ", "เบิกใช้รอบปลูก A", "4,250", "คุณหวาน", "โอนเงิน", "GS-EXP-001", "receipt-001.jpg", "ตรวจแล้ว"],
    ["25/05/2569", accountType, "ค่าแรง", "ดูแลแปลง A1-A12", "6,800", "คุณหวาน", "เงินสด", "GS-EXP-002", "payroll.xlsx", "รออนุมัติ"],
    ["24/05/2569", accountType, "วัสดุปลูก", "ดินปลูกและแกลบดำ", "3,600", "พี่ไกร", "โอนเงิน", "GS-EXP-003", "drive link", "-"],
    ["24/05/2569", accountType, "ระบบน้ำ", "อะไหล่วาล์วน้ำ", "2,150", "พี่สมชาย", "เงินสด", "GS-EXP-004", "receipt-004.jpg", "ซ่อมเดิม"],
    ["23/05/2569", accountType, "ไบโอชา", "ใช้ปรับปรุงดินแปลง B", "1,850", "คุณหวาน", "โอนเงิน", "GS-EXP-005", "photo-005.png", "-"],
    ["23/05/2569", accountType, "น้ำมันรถ", "รถขนของรับวัสดุ", "1,200", "พี่ไกร", "เงินสด", "GS-EXP-006", "receipt-006.jpg", "-"],
    ["22/05/2569", accountType, "ต้นกล้า", "คัดต้นกล้าทดลอง", "5,700", "คุณหวาน", "โอนเงิน", "GS-EXP-007", "invoice-007.pdf", "-"],
    ["22/05/2569", accountType, "เครื่องมือ", "อะไหล่เครื่องพ่นยา", "2,950", "พี่สมชาย", "เงินสด", "GS-EXP-008", "receipt-008.jpg", "-"],
    ["21/05/2569", accountType, "ขนส่ง", "รับวัสดุจากร้านค้า", "980", "พี่ไกร", "เงินสด", "GS-EXP-009", "receipt-009.jpg", "-"],
    ["21/05/2569", accountType, "สารชีวภัณฑ์", "ใช้ในแปลง C", "3,120", "คุณหวาน", "โอนเงิน", "GS-EXP-010", "receipt-010.jpg", "-"],
  ];
  const mappingFields = ["วันที่", "หมวดบัญชี", "รายการ", "รายละเอียด", "จำนวนเงิน", "ผู้จ่าย", "วิธีชำระเงิน", "เลขที่เอกสาร", "แนบหลักฐาน", "หมายเหตุ"];
  const missingColumns = fileName ? [] : ["Upload Excel File"];
  const sampleTotal = previewRows.reduce((sum, row) => sum + Number(row[4].replace(",", "")), 0);
  const confirm = () => {
    onConfirm(accountType, sampleTotal, previewRows.length);
    setImported(true);
  };
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[90] flex items-end bg-goodseed-950/60 p-3 backdrop-blur-sm sm:items-center sm:justify-center">
      <div className="max-h-[92vh] w-full max-w-6xl overflow-hidden rounded-3xl bg-white shadow-2xl">
        <div className="flex flex-col gap-3 border-b border-goodseed-100 p-5 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Import Excel</Badge>
            <h3 className="mt-3 text-2xl font-extrabold text-goodseed-950">Import Accounting Data</h3>
            <p className="mt-1 text-sm font-bold text-goodseed-600">รองรับ .xls, .xlsx, .csv พร้อม Preview, Error Check และ Mapping Columns</p>
          </div>
          <button onClick={onClose} className="rounded-xl bg-goodseed-50 px-4 py-2 text-sm font-extrabold text-goodseed-800 ring-1 ring-goodseed-100">ปิด (Close)</button>
        </div>
        <div className="thin-scrollbar max-h-[76vh] overflow-auto p-5">
          <div className="grid gap-4 lg:grid-cols-[0.8fr_1.2fr]">
            <div className="space-y-4">
              <Select label={<BiLabel th="เลือกหมวดบัญชี" en="Account Type" />} value={accountType} onChange={setAccountType} options={["OPEX", "COGS", "CAPEX", "Revenue", "Payroll"]} />
              <label className="block rounded-2xl border-2 border-dashed border-goodseed-200 bg-goodseed-50 p-5 text-center">
                <Icon name="upload" className="mx-auto h-8 w-8 text-goodseed-700" />
                <p className="mt-3 text-sm font-extrabold text-goodseed-950">Upload Excel File</p>
                <p className="mt-1 text-xs font-bold text-goodseed-600">ลากไฟล์มาวาง หรือกดเลือกไฟล์ .xls / .xlsx / .csv</p>
                <input type="file" accept=".xls,.xlsx,.csv" className="sr-only" onChange={(event) => setFileName(event.target.files?.[0]?.name || "")} />
                <span className="mt-4 inline-flex rounded-xl bg-white px-4 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-100">{fileName || "ยังไม่ได้เลือกไฟล์"}</span>
              </label>
              <Select label={<BiLabel th="เลือก Sheet" en="Sheet" />} value={sheetName} onChange={setSheetName} options={["Sheet 1", "OPEX May", "COGS May", "CAPEX May", "Revenue"]} />
              <div className="rounded-2xl border border-goodseed-100 bg-white p-4">
                <h4 className="text-sm font-extrabold text-goodseed-950">ตรวจสอบ Error</h4>
                {missingColumns.length ? <p className="mt-2 rounded-lg bg-amber-50 p-3 text-sm font-bold text-amber-800">กรุณาเลือกไฟล์ก่อน Import</p> : <p className="mt-2 rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800">ไม่พบคอลัมน์ที่หาย พร้อม Import</p>}
                {imported && <p className="mt-2 rounded-lg bg-goodseed-100 p-3 text-sm font-extrabold text-goodseed-900">Import สำเร็จ: อัปเดตยอดรวม {sampleTotal.toLocaleString("th-TH")} บาท ใน Card แล้ว</p>}
              </div>
              <button onClick={confirm} disabled={!fileName} className="w-full rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-sm disabled:cursor-not-allowed disabled:bg-slate-300">
                ยืนยัน Import
              </button>
            </div>
            <div className="space-y-4">
              <div className="rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4">
                <h4 className="text-sm font-extrabold text-goodseed-950">Mapping Columns</h4>
                <div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                  {mappingFields.map((field) => (
                    <label key={field} className="text-xs font-extrabold text-goodseed-700">
                      {field}
                      <select className="mt-1 w-full rounded-lg border border-goodseed-100 bg-white px-3 py-2 text-xs font-bold outline-none">
                        {mappingFields.map((column) => <option key={column}>{column}</option>)}
                      </select>
                    </label>
                  ))}
                </div>
              </div>
              <div className="rounded-2xl border border-goodseed-100 bg-white p-4">
                <div className="flex items-center justify-between gap-3">
                  <h4 className="text-sm font-extrabold text-goodseed-950">Data Preview 10 แถวแรก</h4>
                  <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{sheetName}</Badge>
                </div>
                <div className="thin-scrollbar mt-3 overflow-x-auto">
                  <table className="min-w-[980px] w-full text-left text-xs">
                    <thead className="bg-goodseed-50 text-goodseed-800"><tr>{mappingFields.map((head) => <th key={head} className="px-3 py-2 font-extrabold">{head}</th>)}</tr></thead>
                    <tbody className="divide-y divide-goodseed-100">{previewRows.map((row, index) => <tr key={index}>{row.map((cell, cellIndex) => <td key={`${index}-${cellIndex}`} className="px-3 py-2 font-semibold text-slate-700">{cell}</td>)}</tr>)}</tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ExpenseSummaryCards({ summaries, period, selected, onOpen, onClose, onImport }) {
  const heads = [
    ["วันที่", "Date"],
    ["ประเภท", "Type"],
    ["หมวดค่าใช้จ่าย", "Category"],
    ["รายละเอียดรายการ", "Item Details"],
    ["จำนวนเงิน", "Amount"],
    ["ผู้บันทึก", "Recorder"],
    ["แปลง / โปรเจกต์", "Plot / Project"],
    ["หลักฐานแนบ", "Evidence"],
    ["หมายเหตุ", "Note"],
  ];
  const statusTone = {
    "ปกติ": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
    "ต้องตรวจสอบ": "bg-amber-100 text-amber-800 ring-amber-200",
    "เกินงบ": "bg-red-100 text-red-700 ring-red-200",
  };
  const cardTone = {
    opex: "border-orange-200 bg-[#fff7ed] text-orange-800",
    cogs: "border-amber-200 bg-[#fffbeb] text-amber-800",
    capex: "border-blue-200 bg-[#eff6ff] text-blue-800",
  };
  const accentTone = {
    opex: "bg-orange-700 text-white ring-orange-700",
    cogs: "bg-goodseed-700 text-white ring-goodseed-700",
    capex: "bg-blue-700 text-white ring-blue-700",
  };
  return (
    <>
      <DashboardPanel title={<BiLabel th="สรุปค่าใช้จ่าย" en="Expense Summary: OPEX / COGS / CAPEX" />}>
        <div className="flex flex-col gap-4">
          {summaries.map((summary) => (
            <div key={summary.key} className={`rounded-2xl border p-5 shadow-sm sm:p-8 ${cardTone[summary.tone]}`}>
              <div className="grid gap-6 xl:grid-cols-[minmax(240px,0.8fr)_minmax(560px,1.7fr)_minmax(190px,0.55fr)] xl:items-center">
                <div className="min-w-0">
                  <Badge className={accentTone[summary.tone]}>{summary.key}</Badge>
                  <h4 className="mt-4 text-2xl font-extrabold leading-snug text-goodseed-950">{summary.th}</h4>
                  <p className="mt-1 text-sm font-bold leading-5 text-goodseed-600">{summary.en}</p>
                  <p className="mt-3 text-sm font-semibold leading-7 text-goodseed-700">{summary.description}</p>
                </div>
                <div className="grid min-w-0 gap-4 md:grid-cols-2 2xl:grid-cols-4">
                  <FinancialMetricBox label="ยอดรวม / Total" value={summary.amount.toLocaleString("th-TH")} unit="บาท" />
                  <FinancialMetricBox label="จำนวนรายการ / Items" value={summary.rowCount.toLocaleString("th-TH")} unit="รายการ" />
                  <FinancialMetricBox label="ช่วงเวลา / Period" value={`${period}`} unit="พ.ค. 2569" />
                  <div className="min-w-[140px] rounded-xl border border-white/70 bg-white/85 p-4 shadow-sm">
                    <p className="min-h-[34px] text-xs font-extrabold leading-5 text-goodseed-600">สถานะงบประมาณ / Budget Status</p>
                    <div className="mt-2 flex min-h-[38px] items-center"><Badge className={statusTone[summary.status]}>{summary.status}</Badge></div>
                  </div>
                </div>
                <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-1">
                  <div className="grid h-14 w-14 place-items-center rounded-2xl bg-white/85 text-goodseed-800 shadow-sm">
                    <Icon name={summary.icon} className="h-7 w-7" />
                  </div>
                  <button onClick={() => onOpen(summary)} className="inline-flex w-full items-center justify-center rounded-xl bg-white px-4 py-3 text-sm font-extrabold leading-5 text-goodseed-900 ring-1 ring-goodseed-100 transition hover:bg-goodseed-50">
                    เปิดดูรายละเอียด / View Details
                  </button>
                  <button data-testid={`finance-import-excel-${summary.key}`} onClick={() => onImport({ key: summary.key })} className="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-4 py-3 text-sm font-extrabold leading-5 text-white shadow-sm transition hover:bg-goodseed-800">
                    <Icon name="upload" className="h-4 w-4" />
                    Import Excel
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </DashboardPanel>
      {selected && (
        <div className="fixed inset-0 z-[80] flex items-end bg-goodseed-950/50 p-3 backdrop-blur-sm sm:items-center sm:justify-center">
          <div className="max-h-[88vh] w-full max-w-6xl overflow-hidden rounded-lg bg-white shadow-2xl">
            <div className="flex flex-col gap-3 border-b border-goodseed-100 p-4 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{selected.key}</Badge>
                <h3 className="mt-2 text-xl font-extrabold text-goodseed-950">{selected.th}</h3>
                <p className="text-sm font-bold text-goodseed-600">{selected.en} Detail Table</p>
              </div>
              <button onClick={onClose} className="rounded-lg bg-goodseed-50 px-4 py-2 text-sm font-extrabold text-goodseed-800 ring-1 ring-goodseed-100">ปิด (Close)</button>
            </div>
            <div className="thin-scrollbar max-h-[68vh] overflow-auto p-4">
              <table className="min-w-[1180px] w-full text-left text-sm">
                <thead className="bg-goodseed-50 text-goodseed-800"><tr>{heads.map(([th, en]) => <th key={th} className="px-3 py-3 font-extrabold"><BiLabel th={th} en={en} /></th>)}</tr></thead>
                <tbody className="divide-y divide-goodseed-100">
                  {selected.rows.map((row) => (
                    <tr key={row.id}>
                      <td className="px-3 py-3 font-bold">{row.date}</td>
                      <td className="px-3 py-3"><Badge className={row.type === "CAPEX" ? "bg-blue-100 text-blue-700 ring-blue-200" : row.layer === "COGS" ? "bg-amber-100 text-amber-800 ring-amber-200" : "bg-orange-100 text-orange-800 ring-orange-200"}>{row.layer === "COGS" ? "COGS" : row.type}</Badge></td>
                      <td className="px-3 py-3 font-bold">{row.category}</td>
                      <td className="px-3 py-3 text-goodseed-900">{row.item}</td>
                      <td className="px-3 py-3 font-extrabold">{row.actual.toLocaleString("th-TH")} บาท</td>
                      <td className="px-3 py-3">{row.recorder}</td>
                      <td className="px-3 py-3">{row.linkTo}</td>
                      <td className="px-3 py-3"><button title="Evidence / Receipt / Attachment" className="rounded-lg bg-white px-2 py-1 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">ดูหลักฐาน (Evidence)</button><p className="mt-1 text-xs text-slate-500">{row.evidence}</p></td>
                      <td className="px-3 py-3 text-slate-600">{row.note}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function RevenueTable({ rows }) {
  return <DashboardPanel title={<BiLabel th="รายรับ" en="Revenue" />}>{rows.map(([name, revenue, count, channel, status]) => <div key={name} className="mb-3 rounded-lg border border-goodseed-100 bg-goodseed-50 p-3"><div className="flex items-start justify-between gap-3"><p className="font-extrabold text-goodseed-950">{name}</p><Badge className="bg-white text-goodseed-800 ring-goodseed-200">{status}</Badge></div><p className="mt-2 text-2xl font-extrabold text-goodseed-800">{revenue.toLocaleString("th-TH")} บาท</p><p className="text-xs font-bold text-goodseed-700">{count} รายการขาย <span className="text-goodseed-500">(Sales)</span> / {channel} <span className="text-goodseed-500">(Channel)</span></p><div className="mt-3 flex flex-wrap gap-2"><button title="Revenue Details" className="rounded-lg bg-white px-3 py-1.5 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">ดูรายละเอียดรายได้ <span className="text-goodseed-500">(Revenue Details)</span></button><a href="#finance" title="Income Entry Form" className="rounded-lg bg-white px-3 py-1.5 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">ไปยังแบบฟอร์มบันทึกรายรับ <span className="text-goodseed-500">(Income Form)</span></a></div></div>)}</DashboardPanel>;
}

function Operations({ role }) {
  return (
    <section className="grid gap-5 xl:grid-cols-3">
      {canAccess(role, "plots") && <InfoPanel id="plots" title="แปลง / พื้นที่ปลูก" icon="map" items={["แปลง A1 ไม้ล้อม 1,250 ต้น", "แปลง A2 ไม้ล้อม 1,204 ต้น", "แปลง B1 แปลงทดลอง GS-03", "ตรวจแปลงครบ 83% วันนี้"]} />}
      {canAccess(role, "workers") && <InfoPanel id="workers" title="คนงาน" icon="users" items={["พี่ไกร: รดน้ำและตรวจระบบน้ำ", "พี่สมชาย: ถอนหญ้าและใส่ปุ๋ย", "ทีมรอบเย็นเริ่ม 16:00 น.", "มีรูปหลักฐาน 22 ภาพ"]} />}
      {canAccess(role, "stock") && <InfoPanel id="stock" title="สต็อกวัสดุ" icon="box" items={["ปุ๋ยอินทรีย์ 132 กระสอบ", "วัสดุคลุมดิน 18 ม้วน", "ยาป้องกันแมลง 24 ลิตร", "เบิกใช้วันนี้ 12 รายการ"]} />}
      {canAccess(role, "equipment") && <FarmAssetsPage role={role} />}
      {canAccess(role, "finance") && <FinanceDashboard role={role} />}
      {canAccess(role, "settings") && <PermissionMatrix role={role} />}
      {canAccess(role, "stock") && <StockMaterialsGuide />}
    </section>
  );
}

function OwnerUserManagementPage({ role }) {
  const [accounts, setAccounts] = useState([]);
  const [ownerDebugCounts, setOwnerDebugCounts] = useState(null);
  const [currentAuthDebug, setCurrentAuthDebug] = useState(null);
  const [userManagementStatus, setUserManagementStatus] = useState("loading");
  const [userManagementMessage, setUserManagementMessage] = useState("");
  const [accountForm, setAccountForm] = useState({
    fullName: "",
    username: "",
    email: "",
    phone: "",
    password: "",
    role: "worker",
  });
  const [savingAccount, setSavingAccount] = useState(false);
  const updateAccountForm = (field, value) => setAccountForm((current) => ({ ...current, [field]: value }));
  const getOwnerAccessToken = async () => {
    const persistedSession = getPersistedSupabaseSession();
    if (persistedSession?.access_token) return persistedSession.access_token;
    const client = getSupabaseClient();
    const { data, error } = await client.auth.getSession();
    if (error) throw error;
    if (!data?.session?.access_token) throw new Error("Owner session is required");
    return data.session.access_token;
  };
  const loadProfiles = async () => {
    if (!isOwnerRole(role)) return;
    setUserManagementStatus("loading");
    try {
      const accessToken = await getOwnerAccessToken();
      let data;
      try {
        data = await supabaseFetch("/rest/v1/profiles?select=id,email,username,full_name,phone,role,requested_role,approval_status,request_note,requested_at,owner_response,disabled,created_at&order=created_at.desc", { accessToken });
      } catch (error) {
        if (!isMissingOptionalProfileColumn(error)) throw error;
        data = await supabaseFetch("/rest/v1/profiles?select=id,email,full_name,phone,role,requested_role,approval_status,request_note,disabled,created_at&order=created_at.desc", { accessToken });
      }
      try {
        const debugData = await supabaseFetch("/rest/v1/rpc/goodseed_owner_debug_counts", { accessToken, method: "POST", body: {} });
        setOwnerDebugCounts(Array.isArray(debugData) ? debugData[0] : debugData);
      } catch (debugError) {
        console.warn("GoodSeed owner debug counts failed", debugError);
      }
      const tokenPayload = decodeJwtPayload(accessToken);
      const currentUser = {
        id: tokenPayload?.sub,
        email: tokenPayload?.email,
      };
      const currentProfile = (data || []).find((profile) => profile.id === currentUser?.id);
      setCurrentAuthDebug({
        id: currentUser?.id || "-",
        email: currentUser?.email || "-",
        status: currentProfile?.approval_status || "-",
      });
      setAccounts((data || []).map((profile) => ({
        id: profile.id,
        fullName: profile.full_name || profile.email,
        email: profile.email,
        username: profile.username || "",
        phone: profile.phone || "-",
        role: normalizeAuthRole(isPrimaryOwnerEmail(profile.email) ? "owner" : profile.role) || "customer",
        requestedRole: normalizeAuthRole(profile.requested_role) || "customer",
        approvalStatus: isPrimaryOwnerEmail(profile.email) ? "approved" : (profile.disabled ? "disabled" : profile.approval_status || "approved"),
        note: profile.request_note || "-",
        requestedAt: profile.requested_at || profile.created_at || "",
        ownerResponse: profile.owner_response || "",
        disabled: Boolean(profile.disabled),
      })));
      setUserManagementStatus("ready");
    } catch (error) {
      setUserManagementMessage(supabaseAuthMessage(error));
      setUserManagementStatus("error");
    }
  };
  useEffect(() => {
    loadProfiles();
  }, [role]);
  const syncAuthProfiles = async () => {
    try {
      setUserManagementStatus("loading");
      setUserManagementMessage("");
      const client = getSupabaseClient();
      const accessToken = await getOwnerAccessToken();
      let result;
      try {
        result = await goodseedAdminUsersRequest("syncAuthProfiles", {}, accessToken);
      } catch (apiError) {
        console.warn("GoodSeed server sync failed; falling back to SQL RPC", apiError);
        try {
          const data = await supabaseFetch("/rest/v1/rpc/goodseed_sync_auth_profiles", { accessToken, method: "POST", body: {} });
          result = Array.isArray(data) ? data[0] : data;
        } catch (rpcError) {
          const { data, error } = await client.rpc("goodseed_sync_auth_profiles");
          if (error) throw apiError;
          result = Array.isArray(data) ? data[0] : data;
        }
      }
      setUserManagementMessage(`ซิงก์ผู้สมัครจาก Supabase Auth แล้ว: profiles ${result?.synced_profiles_count ?? "-"} รายการ, pending ${result?.pending_requests_count ?? "-"} รายการ`);
      await loadProfiles();
    } catch (error) {
      setUserManagementMessage(`ยังซิงก์ไม่ได้: ${supabaseAuthMessage(error)} กรุณารัน supabase/profiles.sql เวอร์ชันล่าสุดใน Supabase SQL Editor ก่อน แล้วกดปุ่ม Sync อีกครั้ง`);
      setUserManagementStatus("error");
    }
  };
  const updateOwnerResponseDraft = (id, value) => {
    setAccounts((current) => current.map((account) => account.id === id ? { ...account, ownerResponse: value } : account));
  };
  const createAccount = async (event) => {
    event.preventDefault();
    if (!accountForm.email.trim() || !accountForm.password.trim()) {
      setUserManagementMessage("กรุณากรอกอีเมลและรหัสผ่านสำหรับบัญชีใหม่");
      return;
    }
    if (accountForm.password.length < 6) {
      setUserManagementMessage("รหัสผ่านต้องมีอย่างน้อย 6 ตัวอักษร");
      return;
    }
    try {
      setSavingAccount(true);
      setUserManagementMessage("");
      const accessToken = await getOwnerAccessToken();
      await goodseedAdminUsersRequest("create", {
        email: accountForm.email.trim().toLowerCase(),
        username: accountForm.username.trim().toLowerCase(),
        password: accountForm.password,
        fullName: accountForm.fullName.trim(),
        phone: accountForm.phone.trim(),
        role: accountForm.role,
      }, accessToken);
      setAccountForm({ fullName: "", username: "", email: "", phone: "", password: "", role: "worker" });
      setUserManagementMessage("สร้างบัญชีผู้ใช้แล้ว / Account created");
      await loadProfiles();
    } catch (error) {
      setUserManagementMessage(`สร้างบัญชีไม่สำเร็จ: ${supabaseAuthMessage(error)}`);
    } finally {
      setSavingAccount(false);
    }
  };
  const resetAccountPassword = async (account) => {
    const nextPassword = window.prompt(`ตั้งรหัสผ่านใหม่สำหรับ ${account.email}`);
    if (!nextPassword) return;
    if (nextPassword.length < 6) {
      setUserManagementMessage("รหัสผ่านต้องมีอย่างน้อย 6 ตัวอักษร");
      return;
    }
    try {
      const accessToken = await getOwnerAccessToken();
      await goodseedAdminUsersRequest("resetPassword", { userId: account.id, password: nextPassword }, accessToken);
      setUserManagementMessage(`รีเซ็ตรหัสผ่านให้ ${account.email} แล้ว`);
    } catch (error) {
      setUserManagementMessage(`รีเซ็ตรหัสผ่านไม่สำเร็จ: ${supabaseAuthMessage(error)}`);
    }
  };
  const updateAccount = async (id, patch) => {
    try {
      const account = accounts.find((item) => item.id === id);
      const accessToken = await getOwnerAccessToken();
      try {
        await goodseedAdminUsersRequest("update", {
          userId: id,
          email: patch.email,
          username: patch.username,
          fullName: patch.fullName,
          phone: patch.phone,
          role: patch.role,
          approvalStatus: patch.approvalStatus,
          disabled: patch.disabled,
          ownerResponse: patch.ownerResponse,
          targetEmail: account?.email || null,
        }, accessToken);
      } catch (apiError) {
        console.warn("GoodSeed server profile update failed; falling back to direct profile update", apiError);
        const approvalStatus = patch.approvalStatus || (patch.disabled ? "disabled" : "approved");
        const profilePatch = {
          ...(patch.email !== undefined ? { email: patch.email } : {}),
          ...(patch.username !== undefined ? { username: patch.username || null } : {}),
          ...(patch.fullName !== undefined ? { full_name: patch.fullName } : {}),
          ...(patch.phone !== undefined ? { phone: patch.phone } : {}),
          ...(patch.role !== undefined ? { role: patch.role, requested_role: patch.role } : {}),
          approval_status: approvalStatus,
          disabled: Boolean(patch.disabled),
          ...(patch.ownerResponse !== undefined ? { owner_response: patch.ownerResponse } : {}),
        };
        await supabaseFetch(`/rest/v1/profiles?id=eq.${encodeURIComponent(id)}`, {
          accessToken,
          method: "PATCH",
          body: profilePatch,
        });
      }
      setUserManagementMessage((current) => current || "บันทึกสิทธิ์ผู้ใช้แล้ว / User permission updated");
      await loadProfiles();
    } catch (error) {
      setUserManagementMessage(`อัปเดตไม่สำเร็จ: ${supabaseAuthMessage(error)}`);
    }
  };
  const statusCounts = accounts.reduce((summary, account) => {
    const status = account.approvalStatus || "approved";
    summary[status] = (summary[status] || 0) + 1;
    return summary;
  }, {});
  const pendingAccounts = accounts.filter((account) => isPendingApprovalStatus(account.approvalStatus));
  const managedAccounts = accounts.filter((account) => account.role !== "customer");
  const disabledAccounts = accounts.filter((account) => account.disabled || account.approvalStatus === "disabled");
  const debugCounts = {
    authUsers: ownerDebugCounts?.auth_users_count ?? null,
    unconfirmed: ownerDebugCounts?.unconfirmed_users_count ?? null,
    profiles: ownerDebugCounts?.profiles_count ?? accounts.length,
    pending: ownerDebugCounts?.pending_requests_count ?? 0,
    approved: ownerDebugCounts?.approved_users_count ?? accounts.filter((account) => account.approvalStatus === "approved").length,
  };

  if (!isOwnerRole(role)) {
    return <InfoPanel id="owner-only-user-management" title="Owner Only" icon="shield" items={["หน้านี้เปิดให้เฉพาะ Owner เจ้าของฟาร์มเท่านั้น", "ผู้ใช้งานทั่วไปไม่สามารถจัดการสิทธิ์หรืออนุมัติบัญชีได้"]} />;
  }

  return (
    <section className="space-y-5">
      <SectionHeader
        title="Owner User Management"
        subtitle="จัดการผู้สมัคร อนุมัติ ปฏิเสธ เปลี่ยน Role รีเซ็ตรหัสผ่าน และปิดการใช้งานบัญชี"
        action={<Badge className="bg-goodseed-700 text-white ring-goodseed-700">Owner Only</Badge>}
      />
      <DashboardPanel title="Create Account" action={<Badge className="bg-white text-goodseed-800 ring-goodseed-200">Owner can create directly</Badge>}>
        <form onSubmit={createAccount} className="grid gap-3 lg:grid-cols-6 lg:items-end">
          <Input label="Full Name" value={accountForm.fullName} onChange={(value) => updateAccountForm("fullName", value)} />
          <Input label="Username" value={accountForm.username} onChange={(value) => updateAccountForm("username", value)} />
          <Input label="Email" type="email" value={accountForm.email} onChange={(value) => updateAccountForm("email", value)} />
          <Input label="Phone" value={accountForm.phone} onChange={(value) => updateAccountForm("phone", value)} />
          <label className="block text-sm font-extrabold text-goodseed-900">
            Role
            <select value={accountForm.role} onChange={(event) => updateAccountForm("role", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100">
              {ownerManagedRoleOptions.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}
            </select>
          </label>
          <Input label="Password" type="password" value={accountForm.password} onChange={(value) => updateAccountForm("password", value)} />
          <button type="submit" disabled={savingAccount} className="rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-sm hover:bg-goodseed-800 disabled:bg-goodseed-300 lg:col-span-6">
            {savingAccount ? "Creating..." : "Create Owner-Managed Account"}
          </button>
        </form>
      </DashboardPanel>
      <div className="grid gap-3 md:grid-cols-4">
        {[
          ["Managed", managedAccounts.length, "Owner-created accounts"],
          ["Approved", statusCounts.approved || statusCounts.active || 0, "ใช้งานได้"],
          ["Roles", ownerManagedRoleOptions.length, "สิทธิ์ที่ Owner กำหนด"],
          ["Disabled", disabledAccounts.length, "ปิดการใช้งาน"],
        ].map(([label, value, hint]) => (
          <div key={label} className="rounded-2xl border border-goodseed-100 bg-white p-4 shadow-sm">
            <p className="text-xs font-extrabold uppercase tracking-[0.14em] text-goodseed-500">{label}</p>
            <p className="mt-2 text-3xl font-extrabold text-goodseed-950">{value}</p>
            <p className="text-sm font-bold text-goodseed-700">{hint}</p>
          </div>
        ))}
      </div>
      <DashboardPanel title="Owner Debug Panel" action={<button type="button" onClick={syncAuthProfiles} className="inline-flex items-center gap-2 rounded-xl bg-goodseed-700 px-4 py-2 text-xs font-extrabold text-white shadow-sm hover:bg-goodseed-800"><Icon name="refresh" className="h-4 w-4" />Sync Auth Users</button>}>
        <div className="grid gap-3 md:grid-cols-5">
          <div className="rounded-xl bg-goodseed-50 p-4"><p className="text-xs font-black text-goodseed-500">profiles</p><p className="mt-1 text-2xl font-black text-goodseed-950">{debugCounts.profiles}</p></div>
          <div className="rounded-xl bg-amber-50 p-4"><p className="text-xs font-black text-amber-700">pending requests</p><p className="mt-1 text-2xl font-black text-amber-900">{debugCounts.pending}</p></div>
          <div className="rounded-xl bg-goodseed-50 p-4"><p className="text-xs font-black text-goodseed-500">approved users</p><p className="mt-1 text-2xl font-black text-goodseed-950">{debugCounts.approved}</p></div>
          <div className="rounded-xl bg-slate-50 p-4"><p className="text-xs font-black text-slate-500">auth.users</p><p className="mt-1 text-2xl font-black text-slate-900">{debugCounts.authUsers ?? "-"}</p></div>
          <div className="rounded-xl bg-red-50 p-4"><p className="text-xs font-black text-red-600">unconfirmed</p><p className="mt-1 text-2xl font-black text-red-800">{debugCounts.unconfirmed ?? "-"}</p></div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-3">
          <div className="rounded-xl bg-white p-4 ring-1 ring-goodseed-100"><p className="text-xs font-black text-goodseed-500">Current User ID</p><p className="mt-1 break-words text-sm font-black text-goodseed-950">{currentAuthDebug?.id || "-"}</p></div>
          <div className="rounded-xl bg-white p-4 ring-1 ring-goodseed-100"><p className="text-xs font-black text-goodseed-500">Current User Email</p><p className="mt-1 break-words text-sm font-black text-goodseed-950">{currentAuthDebug?.email || "-"}</p></div>
          <div className="rounded-xl bg-white p-4 ring-1 ring-goodseed-100"><p className="text-xs font-black text-goodseed-500">Current Profile Status</p><p className="mt-1 text-sm font-black text-goodseed-950">{currentAuthDebug?.status || "-"}</p></div>
        </div>
        <p className="mt-3 text-xs font-bold leading-6 text-goodseed-700">ผู้สมัครจากหน้า Sign Up จะถูกสร้างเป็น profile สถานะ pending และแสดงใน Approval Queue หลังรัน supabase/profiles.sql เวอร์ชันล่าสุด</p>
      </DashboardPanel>
      {userManagementMessage && <div className="rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4 text-sm font-bold leading-7 text-goodseed-800">{userManagementMessage}</div>}
      <DashboardPanel title="User Approval Queue" action={<Badge className="bg-white text-goodseed-800 ring-goodseed-200">{pendingAccounts.length} pending</Badge>}>
        {userManagementStatus === "loading" && <p className="rounded-xl bg-goodseed-50 p-4 text-sm font-bold text-goodseed-700">กำลังโหลดคำขอสมัคร...</p>}
        {pendingAccounts.length === 0 ? (
          <div className="rounded-2xl border border-amber-100 bg-amber-50 p-5 text-sm font-bold leading-7 text-amber-900">
            ยังไม่มีคำขอรออนุมัติ ถ้าหุ้นส่วนหรือทีมงานสมัครแล้วไม่ขึ้น ให้รันไฟล์ <span className="font-black">supabase/profiles.sql</span> เวอร์ชันล่าสุดใน Supabase SQL Editor แล้วกด Sync Auth Users
          </div>
        ) : (
          <div className="thin-scrollbar overflow-x-auto">
            <table className="min-w-full text-left text-sm">
              <thead className="bg-goodseed-50 text-xs uppercase text-goodseed-700">
                <tr>
                  {["ผู้สมัคร", "อีเมล", "สถานะ", "วันที่ขอสิทธิ์", "Role ปัจจุบัน", "ขอสิทธิ์", "หมายเหตุ", "ตอบกลับ Owner", "จัดการ"].map((header) => (
                    <th key={header} className="whitespace-nowrap px-4 py-3 font-black">{header}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-goodseed-100">
                {pendingAccounts.map((account) => (
                  <tr key={account.id} className="bg-white align-top">
                    <td className="px-4 py-3 font-extrabold text-goodseed-950">{account.fullName}</td>
                    <td className="px-4 py-3 font-bold text-goodseed-700">{account.email}</td>
                    <td className="px-4 py-3"><Badge className="bg-amber-100 text-amber-800 ring-amber-200">{account.approvalStatus}</Badge></td>
                    <td className="px-4 py-3 font-bold text-goodseed-700">{account.requestedAt ? new Date(account.requestedAt).toLocaleString("th-TH") : "-"}</td>
                    <td className="px-4 py-3"><Badge className={roleInfo(account.role).badge}>{roleInfo(account.role).label}</Badge></td>
                    <td className="px-4 py-3"><Badge className={roleInfo(account.requestedRole).badge}>{roleInfo(account.requestedRole).label}</Badge></td>
                    <td className="min-w-[180px] px-4 py-3 text-xs font-bold leading-6 text-goodseed-700">{account.note}</td>
                    <td className="min-w-[220px] px-4 py-3">
                      <textarea value={account.ownerResponse} onChange={(event) => updateOwnerResponseDraft(account.id, event.target.value)} rows="2" className="w-full resize-none rounded-xl border border-goodseed-100 bg-white px-3 py-2 text-xs font-bold text-goodseed-800 outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="ข้อความถึงผู้สมัคร" />
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex min-w-[190px] flex-wrap gap-2">
                        <button type="button" onClick={() => updateAccount(account.id, { role: account.requestedRole, approvalStatus: "approved", disabled: false, ownerResponse: account.ownerResponse })} className="rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white hover:bg-goodseed-800">Approve</button>
                        <button type="button" onClick={() => updateAccount(account.id, { role: account.role, approvalStatus: "rejected", disabled: false, ownerResponse: account.ownerResponse || "Owner rejected this request" })} className="rounded-lg border border-red-100 bg-red-50 px-3 py-2 text-xs font-extrabold text-red-700 hover:bg-red-100">Reject</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </DashboardPanel>
      <DashboardPanel title="Admin Panel / User Management" action={<Badge className="bg-white text-goodseed-800 ring-goodseed-200">{managedAccounts.length} users</Badge>}>
        {userManagementStatus === "loading" && <p className="rounded-xl bg-goodseed-50 p-4 text-sm font-bold text-goodseed-700">กำลังโหลดข้อมูลผู้ใช้จาก Supabase...</p>}
        <div className="thin-scrollbar overflow-x-auto">
          <table className="min-w-[1360px] w-full text-left text-sm">
            <thead className="bg-goodseed-50 text-goodseed-800">
              <tr>
                <th className="px-3 py-3">ผู้ใช้</th>
                <th className="px-3 py-3">อีเมล</th>
                <th className="px-3 py-3">Username</th>
                <th className="px-3 py-3">สถานะ</th>
                <th className="px-3 py-3">Role</th>
                <th className="px-3 py-3">Phone</th>
                <th className="px-3 py-3">Owner Note</th>
                <th className="px-3 py-3">จัดการ</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-goodseed-100">
              {managedAccounts.map((account) => {
                const status = account.approvalStatus || account.status || "approved";
                const locked = isPrimaryOwnerEmail(account.email);
                return (
                  <tr key={account.id} className={locked ? "bg-goodseed-50/70" : "bg-white"}>
                    <td className="px-3 py-3">
                      {locked ? (
                        <p className="font-extrabold text-goodseed-950">{account.fullName || "-"}</p>
                      ) : (
                        <input value={account.fullName || ""} onChange={(event) => setAccounts((current) => current.map((item) => item.id === account.id ? { ...item, fullName: event.target.value } : item))} className="w-52 rounded-lg border border-goodseed-100 bg-white px-3 py-2 text-sm font-bold text-goodseed-950 outline-none" />
                      )}
                      <p className="text-xs font-bold text-goodseed-600">{account.phone || "-"}</p>
                    </td>
                    <td className="px-3 py-3 font-bold text-slate-700">{account.email}</td>
                    <td className="px-3 py-3">
                      {locked ? (
                        <span className="font-bold text-goodseed-700">{account.username || "-"}</span>
                      ) : (
                        <input value={account.username || ""} onChange={(event) => setAccounts((current) => current.map((item) => item.id === account.id ? { ...item, username: event.target.value } : item))} className="w-40 rounded-lg border border-goodseed-100 bg-white px-3 py-2 text-sm font-bold text-goodseed-950 outline-none" />
                      )}
                    </td>
                    <td className="px-3 py-3"><Badge className={accountStatusTone(status)}>{status}</Badge></td>
                    <td className="px-3 py-3">
                      {locked ? (
                        <Badge className={roleInfo(account.role).badge}>{roleInfo(account.role).label}</Badge>
                      ) : (
                        <select value={account.role || "worker"} onChange={(event) => setAccounts((current) => current.map((item) => item.id === account.id ? { ...item, role: event.target.value } : item))} className="rounded-xl border border-goodseed-100 bg-white px-3 py-2 text-sm font-bold text-goodseed-900 outline-none">
                          {ownerManagedRoleOptions.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}
                        </select>
                      )}
                    </td>
                    <td className="px-3 py-3">
                      {locked ? (
                        <span className="font-bold text-goodseed-700">{account.phone || "-"}</span>
                      ) : (
                        <input value={account.phone === "-" ? "" : account.phone || ""} onChange={(event) => setAccounts((current) => current.map((item) => item.id === account.id ? { ...item, phone: event.target.value } : item))} className="w-36 rounded-lg border border-goodseed-100 bg-white px-3 py-2 text-sm font-bold text-goodseed-950 outline-none" />
                      )}
                    </td>
                    <td className="min-w-64 px-3 py-3">
                      {locked ? (
                        <p className="text-xs font-bold text-goodseed-600">บัญชี Owner หลัก</p>
                      ) : (
                        <div className="space-y-2">
                          <textarea
                            value={account.ownerResponse || ""}
                            onChange={(event) => updateOwnerResponseDraft(account.id, event.target.value)}
                            className="min-h-20 w-full rounded-xl border border-goodseed-100 bg-white px-3 py-2 text-sm font-semibold text-goodseed-900 outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100"
                            placeholder="ข้อความตอบกลับจาก Owner เช่น อนุมัติแล้ว / รอเอกสารเพิ่ม / ติดต่อกลับ..."
                          />
                          <button type="button" onClick={() => updateAccount(account.id, { ownerResponse: account.ownerResponse || "" })} className="rounded-lg bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">บันทึกข้อความ</button>
                        </div>
                      )}
                    </td>
                    <td className="px-3 py-3">
                      {locked ? (
                        <Badge className="bg-goodseed-700 text-white ring-goodseed-700">Bootstrap Owner</Badge>
                      ) : (
                        <div className="flex flex-wrap gap-2">
                          <button type="button" onClick={() => updateAccount(account.id, { ...account, disabled: false })} className="rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white">Save</button>
                          <button type="button" onClick={() => resetAccountPassword(account)} className="rounded-lg bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-200">Reset Password</button>
                          <button type="button" onClick={() => updateAccount(account.id, { disabled: !account.disabled, ownerResponse: account.ownerResponse })} className="rounded-lg bg-red-100 px-3 py-2 text-xs font-extrabold text-red-700">{account.disabled ? "Enable" : "Disable"}</button>
                        </div>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {managedAccounts.length === 0 && userManagementStatus !== "loading" && (
          <div className="mt-4 rounded-xl bg-amber-50 p-4 text-sm font-bold leading-7 text-amber-900">
            ยังไม่พบบัญชีที่ Owner สร้างไว้ ให้ใช้ฟอร์ม Create Account ด้านบนเพื่อสร้างบัญชีพนักงานก่อนใช้งาน
          </div>
        )}
      </DashboardPanel>
    </section>
  );
}

function PermissionMatrix({ role }) {
  const pages = [
    ["Dashboard", "dashboard"],
    ["ระบบรายงานประจำวัน", "report-form"],
    ["QR Management", "report-form"],
    ["ตารางงาน", "responsibility"],
    ["People / HR", "people-hr"],
    ["ข้อมูลต้นไม้", "trees"],
    ["คลังวัสดุ", "stock"],
    ["การเงิน", "finance"],
    ["OPEX / COGS / CAPEX", "finance"],
    ["Unit Cost", "finance"],
    ["UI Flow Map / Developer Tools", "ui-flow-map"],
    ["Preview Deployment / Share Preview", "preview-deployment"],
    ["Owner User Management", "user-management"],
    ["ตั้งค่าระบบ", "settings"],
    ["จัดการผู้ใช้งาน", "settings"],
  ];
  const managedRoles = roleOptions.filter((item) => ["owner", "partner_owner", "admin", "manager", "plot_manager", "staff", "worker"].includes(item.id));
  const [permissionOverrides, setPermissionOverrides] = useState(readPermissionOverrides);
  const [permissionMessage, setPermissionMessage] = useState("");
  const isOwner = isOwnerRole(role);
  const isAllowed = (roleId, pageId) => effectivePermissions(pageId, permissionOverrides).includes(roleId);
  const togglePermission = (roleId, pageId) => {
    if (!isOwner || roleId === "owner") return;
    const current = effectivePermissions(pageId, permissionOverrides);
    const nextRoles = current.includes(roleId)
      ? current.filter((item) => item !== roleId)
      : [...current, roleId];
    const nextOverrides = { ...permissionOverrides, [pageId]: Array.from(new Set(["owner", "partner_owner", ...nextRoles])) };
    setPermissionOverrides(nextOverrides);
    writePermissionOverrides(nextOverrides);
    setPermissionMessage("บันทึกสิทธิ์แล้ว");
  };
  const resetPermissions = () => {
    if (!window.confirm("ต้องการคืนค่า Permission Matrix เป็นค่าเริ่มต้นหรือไม่")) return;
    setPermissionOverrides({});
    writePermissionOverrides({});
    setPermissionMessage("คืนค่าสิทธิ์เริ่มต้นแล้ว");
  };

  return (
    <div id="settings" className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft xl:col-span-3">
      <SectionHeader
        title="ตั้งค่าระบบและสิทธิ์ผู้ใช้งาน"
        subtitle="Permission Matrix สำหรับ Owner, Admin / Manager, Staff และ Customer โดย Owner เป็นผู้กำหนดสิทธิ์"
        action={<Badge className={roleInfo(role).badge}>{roleInfo(role).label}</Badge>}
      />
      <div className="mb-4 grid gap-3 lg:grid-cols-[1fr_auto] lg:items-center">
        <div className="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm font-bold leading-7 text-amber-900">
          การตั้งค่าสิทธิ์นี้ใช้สำหรับควบคุมเมนูในหน้าเว็บ และควรตรวจสิทธิ์ฝั่ง Backend ทุกครั้งเมื่อเชื่อมระบบข้อมูลจริง
        </div>
        {isOwner && (
          <div className="flex flex-wrap gap-2">
            {permissionMessage && <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{permissionMessage}</Badge>}
            <button type="button" onClick={resetPermissions} className="rounded-xl border border-goodseed-200 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 transition hover:bg-goodseed-50">คืนค่าเริ่มต้น</button>
          </div>
        )}
      </div>
      <div className="thin-scrollbar overflow-x-auto">
        <table className="min-w-[860px] w-full text-left text-sm">
          <thead className="bg-goodseed-50 text-goodseed-800"><tr><th className="px-3 py-3">หน้า / Module</th>{managedRoles.map((item) => <th key={item.id} className="px-3 py-3">{item.label}</th>)}</tr></thead>
          <tbody className="divide-y divide-goodseed-100">
            {pages.map(([label, pageId]) => (
              <tr key={label}>
                <td className="px-3 py-3 font-extrabold text-goodseed-900">{label}</td>
                {managedRoles.map((item) => {
                  const allowed = isAllowed(item.id, pageId);
                  const locked = item.id === "owner" || !isOwner;
                  return (
                    <td key={item.id} className="px-3 py-3">
                      <button
                        type="button"
                        disabled={locked}
                        onClick={() => togglePermission(item.id, pageId)}
                        className={`inline-flex min-w-24 items-center justify-center rounded-full px-3 py-2 text-xs font-extrabold ring-1 transition ${allowed ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : "bg-slate-100 text-slate-500 ring-slate-200"} ${locked ? "cursor-not-allowed opacity-75" : "hover:scale-[1.02] hover:shadow-sm"}`}
                        title={locked ? "Owner เท่านั้นที่แก้ไขสิทธิ์ได้" : "กดเพื่อสลับ อนุญาต / ไม่อนุญาต"}
                      >
                        {allowed ? "อนุญาต" : "ไม่อนุญาต"}
                      </button>
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <CrudSystemManager role={role} />
    </div>
  );
}

function StockMaterialsGuide() {
  const stockImages = [
    { title: "ตัวอย่างสินค้าสต๊อกวัตถุดิบ", src: stockMaterialsGuide, detail: "รายการวัสดุที่ต้องนำเข้าและเบิกใช้ในสวน" },
    { title: "แบบฟอร์มเขียนเบิกและใช้วัตถุดิบ", src: stockMaterialsWithdrawalForm, detail: "บันทึกการนำเข้า เบิกใช้ วัสดุคงเหลือ และการตรวจสอบประจำวัน" },
  ];

  return (
    <div className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft xl:col-span-3">
      <SectionHeader
        title="สต็อกวัตถุดิบและแบบฟอร์มเบิกใช้"
        subtitle="ภาพรายการวัสดุและแบบฟอร์มบันทึกการนำเข้า/เบิกใช้ประจำวัน"
        action={<Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">สต็อกวัสดุ</Badge>}
      />
      <div className="grid gap-5 lg:grid-cols-2">
        {stockImages.map((item) => (
          <a key={item.src} href={item.src} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-lg border border-goodseed-100 bg-goodseed-50">
            <div className="grid place-items-center bg-white p-2">
              <img src={item.src} alt={item.title} className="max-h-[760px] w-full object-contain" />
            </div>
            <div className="border-t border-goodseed-100 bg-white p-4">
              <p className="font-extrabold text-goodseed-900">{item.title}</p>
              <p className="mt-1 text-sm text-goodseed-700">{item.detail}</p>
            </div>
          </a>
        ))}
      </div>
    </div>
  );
}

function PeopleStatusBadge({ status }) {
  return <Badge className={peopleStatusClasses[status] || peopleStatusClasses.Offline}>{status}</Badge>;
}

function EmployeeAvatar({ employee }) {
  return (
    <div className="grid h-14 w-14 shrink-0 place-items-center overflow-hidden rounded-2xl bg-gradient-to-br from-goodseed-700 to-goodseed-400 text-lg font-black text-white shadow-sm">
      {employee.photo ? <img src={employee.photo} alt={`รูปโปรไฟล์ ${employee.name}`} className="h-full w-full object-cover" /> : employee.short}
    </div>
  );
}

function EmployeeCard({ employee, onOpen, onEdit, onArchive, canManage }) {
  const alerts = employee.alerts || [];
  const mini = employee.mini || { done: 0, lastCheck: "-", lastReport: "-", score: employee.kpi || 0 };
  const alertTone = alerts.some((item) => item.includes("KPI") || item.includes("ขาดงาน") || item.includes("ปัญหา")) ? "bg-red-50 text-red-700 ring-red-100" : "bg-amber-50 text-amber-800 ring-amber-100";
  return (
    <article className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft transition hover:-translate-y-0.5 hover:border-goodseed-300 hover:shadow-lg">
      <div className="flex items-start gap-3">
        <EmployeeAvatar employee={employee} />
        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-start justify-between gap-2">
            <div className="min-w-0">
              <h3 className="truncate text-lg font-black text-goodseed-950">{employee.name}</h3>
              <p className="text-xs font-bold text-goodseed-600">{employee.position}</p>
            </div>
            <div className="flex flex-wrap justify-end gap-2">
              <PeopleStatusBadge status={employee.status} />
              {employee.hrStatus && employee.hrStatus !== "ทำงานอยู่" && <Badge className="bg-slate-100 text-slate-700 ring-slate-200">{employee.hrStatus}</Badge>}
            </div>
          </div>
          <div className="mt-3 flex flex-wrap gap-2">
            {alerts.length ? alerts.map((alert) => <Badge key={alert} className={alertTone}>{alert}</Badge>) : <Badge className="bg-goodseed-50 text-goodseed-700 ring-goodseed-100">ไม่มีแจ้งเตือน</Badge>}
          </div>
        </div>
      </div>
      <div className="mt-4 grid gap-2 sm:grid-cols-2">
        <MiniMetric label="พื้นที่รับผิดชอบ" value={employee.plot} />
        <MiniMetric label="ต้นไม้ที่ดูแล" value={`${Number(employee.trees || 0).toLocaleString("th-TH")} ต้น`} />
        <MiniMetric label="คนงานในทีม" value={`${employee.team} คน`} />
        <MiniMetric label="KPI ล่าสุด" value={`${employee.kpi}%`} danger={employee.kpi < 75} />
      </div>
      <div className="mt-4 grid gap-2 text-xs font-bold text-goodseed-700 sm:grid-cols-2">
        <span className="rounded-lg bg-goodseed-50 p-2">งานเสร็จวันนี้: {mini.done}</span>
        <span className="rounded-lg bg-goodseed-50 p-2">ตรวจแปลงล่าสุด: {mini.lastCheck}</span>
        <span className="rounded-lg bg-goodseed-50 p-2">ส่งรายงาน: {mini.lastReport}</span>
        <span className="rounded-lg bg-goodseed-50 p-2">คะแนนประเมิน: {mini.score}</span>
      </div>
      <div className="mt-4 rounded-lg bg-white p-3 ring-1 ring-goodseed-100">
        <p className="text-xs font-bold text-goodseed-600">สวัสดิการที่ได้รับ</p>
        <p className="mt-1 text-sm font-extrabold text-goodseed-900">{employee.welfare}</p>
        <p className="mt-1 text-xs font-bold text-goodseed-600">เริ่มงาน: {employee.startDate}</p>
      </div>
      <div className={`mt-4 grid gap-2 ${canManage ? "grid-cols-2 sm:grid-cols-4" : "grid-cols-2"}`}>
        <button onClick={() => onOpen(employee)} className="rounded-lg bg-goodseed-700 px-3 py-2 text-sm font-black text-white">ดูโปรไฟล์</button>
        <button onClick={() => onOpen(employee)} className="rounded-lg bg-goodseed-50 px-3 py-2 text-sm font-black text-goodseed-800 ring-1 ring-goodseed-100">ดูรายงาน</button>
        {canManage && <button onClick={() => onEdit(employee)} className="inline-flex items-center justify-center gap-1 rounded-lg bg-white px-3 py-2 text-sm font-black text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-50"><Icon name="edit" className="h-4 w-4" />แก้ไข</button>}
        {canManage && <button onClick={() => onArchive(employee)} className="inline-flex items-center justify-center gap-1 rounded-lg bg-red-50 px-3 py-2 text-sm font-black text-red-700 ring-1 ring-red-100 hover:bg-red-100"><Icon name="trash" className="h-4 w-4" />ปิดใช้</button>}
      </div>
    </article>
  );
}

function EmployeeSlidePanel({ employee, onClose, onEdit, canManage }) {
  if (!employee) return null;
  const alerts = employee.alerts || [];
  const family = employee.family || {};
  const detailRows = [
    ["โปรไฟล์พนักงาน", `${employee.name} / ${employee.position}`],
    ["KPI", `${employee.kpi}% / งานเสร็จวันนี้ ${employee.mini?.done || 0} งาน`],
    ["รายงานล่าสุด", employee.mini?.lastReport || "-"],
    ["ตารางงาน", `${employee.plot} / ทีม ${employee.team} คน`],
    ["เอกสารพนักงาน", alerts.includes("เอกสารใกล้หมดอายุ") ? "มีเอกสารใกล้หมดอายุ" : "เอกสารครบ"],
    ["สวัสดิการ", employee.welfare],
    ["ประวัติการทำงาน", `เริ่มงาน ${employee.startDate}`],
  ];
  return (
    <div className="fixed inset-0 z-[90] bg-goodseed-950/45 backdrop-blur-sm">
      <button className="absolute inset-0 h-full w-full cursor-default" onClick={onClose} aria-label="ปิดโปรไฟล์" />
      <aside className="thin-scrollbar absolute inset-y-0 right-0 w-full max-w-xl overflow-y-auto bg-white p-5 shadow-2xl">
        <div className="flex items-start justify-between gap-4">
          <div className="flex items-center gap-3">
            <EmployeeAvatar employee={employee} />
            <div>
              <h3 className="text-2xl font-black text-goodseed-950">{employee.name}</h3>
              <p className="font-bold text-goodseed-600">{employee.position}</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {canManage && <button onClick={() => onEdit(employee)} className="rounded-lg bg-goodseed-700 px-3 py-2 text-sm font-black text-white">แก้ไขข้อมูล</button>}
            <button onClick={onClose} className="rounded-lg bg-goodseed-50 p-2 text-goodseed-800 ring-1 ring-goodseed-100"><Icon name="x" /></button>
          </div>
        </div>
        <div className="mt-4 flex flex-wrap gap-2">
          <PeopleStatusBadge status={employee.status} />
          <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{employee.role}</Badge>
          <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{employee.department}</Badge>
        </div>
        <img src={employee.latestWorkImage || employee.photo || "/public/farm-assets/goodseed-logo.png"} alt={`รูปงานล่าสุดของ ${employee.name}`} className="mt-5 h-52 w-full rounded-lg object-cover ring-1 ring-goodseed-100" />
        <div className="mt-5 grid gap-3 sm:grid-cols-2">
          {detailRows.map(([label, value]) => <MiniMetric key={label} label={label} value={value} danger={label === "KPI" && employee.kpi < 75} />)}
        </div>
        <div className="mt-5 rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
          <h4 className="font-black text-goodseed-950">Welfare & Family</h4>
          <div className="mt-3 grid gap-2 text-sm font-bold text-goodseed-800 sm:grid-cols-2">
            <span>สถานะครอบครัว: {family.status || "-"}</span>
            <span>จำนวนบุตร: {family.children ?? "-"}</span>
            <span>ผู้ติดต่อฉุกเฉิน: {family.emergency || "-"}</span>
            <span>ทุนการศึกษา: {family.education || "-"}</span>
            <span className="sm:col-span-2">กิจกรรม: {family.activity || "-"}</span>
          </div>
        </div>
        <div className="mt-5 rounded-lg border border-goodseed-100 bg-white p-4">
          <h4 className="font-black text-goodseed-950">Notification Badge</h4>
          <div className="mt-3 flex flex-wrap gap-2">
            {alerts.length ? alerts.map((alert) => <Badge key={alert} className="bg-amber-50 text-amber-800 ring-amber-100">{alert}</Badge>) : <Badge className="bg-goodseed-50 text-goodseed-800 ring-goodseed-100">ปกติ</Badge>}
          </div>
        </div>
      </aside>
    </div>
  );
}

function PeopleRecordModal({ mode, initialRecord, onClose, onSave }) {
  const [form, setForm] = useState(() => {
    const family = initialRecord?.family || {};
    return {
      id: initialRecord?.id || `HR-${Date.now()}`,
      name: initialRecord?.name || "",
      short: initialRecord?.short || "",
      department: initialRecord?.department || "Farm Worker",
      position: initialRecord?.position || "คนงาน",
      status: initialRecord?.status || "Working",
      plot: initialRecord?.plot || "แปลง A",
      trees: initialRecord?.trees || 0,
      team: initialRecord?.team || 1,
      kpi: initialRecord?.kpi || 80,
      welfare: initialRecord?.welfare || "ประกันสังคม",
      startDate: initialRecord?.startDate || "28 พ.ค. 2569",
      role: initialRecord?.role || "Staff",
      photo: initialRecord?.photo || "",
      latestWorkImage: initialRecord?.latestWorkImage || "",
      phone: initialRecord?.phone || "",
      hrStatus: initialRecord?.hrStatus || "ทำงานอยู่",
      note: initialRecord?.note || "",
      alertsText: (initialRecord?.alerts || []).join(", "),
      familyStatus: family.status || "โสด",
      children: family.children || 0,
      emergency: family.emergency || "",
      education: family.education || "",
      familyActivity: family.activity || "",
    };
  });
  const setField = (key, value) => setForm((current) => ({ ...current, [key]: value }));
  const handleImage = async (key, file) => {
    if (!file) return;
    const dataUrl = await readImageFile(file);
    setField(key, dataUrl);
  };
  const handleSave = () => {
    const safeName = form.name.trim() || "พนักงานใหม่";
    const alerts = form.alertsText.split(",").map((item) => item.trim()).filter(Boolean);
    const kpiValue = Number(form.kpi) || 0;
    onSave({
      ...initialRecord,
      id: form.id,
      name: safeName,
      short: form.short.trim() || safeName.slice(0, 2),
      department: form.department,
      position: form.position,
      status: form.status,
      plot: form.plot,
      trees: Number(form.trees) || 0,
      team: Number(form.team) || 0,
      kpi: kpiValue,
      welfare: form.welfare,
      startDate: form.startDate,
      role: form.role,
      photo: form.photo,
      latestWorkImage: form.latestWorkImage || form.photo || initialRecord?.latestWorkImage || "/public/farm-assets/goodseed-logo.png",
      phone: form.phone,
      hrStatus: form.hrStatus,
      note: form.note,
      alerts,
      mini: initialRecord?.mini || { done: 0, lastCheck: "-", lastReport: "-", score: kpiValue },
      family: {
        status: form.familyStatus,
        children: Number(form.children) || 0,
        emergency: form.emergency,
        education: form.education,
        activity: form.familyActivity,
      },
      updatedAt: new Date().toLocaleString("th-TH"),
    });
  };

  return (
    <div className="fixed inset-0 z-[95] grid place-items-center bg-goodseed-950/50 p-4 backdrop-blur-sm">
      <div className="thin-scrollbar max-h-[92vh] w-full max-w-5xl overflow-y-auto rounded-2xl bg-white shadow-2xl">
        <div className="flex items-start justify-between gap-4 border-b border-goodseed-100 p-5">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.18em] text-goodseed-500">People / HR</p>
            <h3 className="text-2xl font-black text-goodseed-950">{mode === "edit" ? "แก้ไขข้อมูลบุคลากร" : "เพิ่มข้อมูลบุคลากรใหม่"}</h3>
            <p className="mt-1 text-sm font-semibold text-goodseed-700">กรอกข้อมูล โปรไฟล์ รูปภาพ สิทธิ์ และรายละเอียดสวัสดิการได้จากหน้าต่างเดียว</p>
          </div>
          <button onClick={onClose} className="rounded-lg bg-goodseed-50 p-2 text-goodseed-800 ring-1 ring-goodseed-100"><Icon name="x" /></button>
        </div>

        <div className="grid gap-5 p-5 lg:grid-cols-[220px_1fr]">
          <div className="space-y-4">
            <div className="rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4">
              <p className="text-sm font-black text-goodseed-900">รูปโปรไฟล์</p>
              <div className="mt-3 grid aspect-square place-items-center overflow-hidden rounded-2xl bg-white ring-1 ring-goodseed-100">
                {form.photo ? <img src={form.photo} alt="รูปโปรไฟล์พนักงาน" className="h-full w-full object-cover" /> : <Icon name="users" className="h-12 w-12 text-goodseed-300" />}
              </div>
              <label className="mt-3 flex cursor-pointer items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-3 py-2 text-sm font-black text-white">
                <Icon name="upload" className="h-4 w-4" /> เพิ่มรูปภาพ
                <input type="file" accept="image/*" className="hidden" onChange={(event) => handleImage("photo", event.target.files?.[0])} />
              </label>
            </div>
            <div className="rounded-2xl border border-goodseed-100 bg-white p-4">
              <p className="text-sm font-black text-goodseed-900">รูปงานล่าสุด / หลักฐาน</p>
              <div className="mt-3 h-28 overflow-hidden rounded-xl bg-goodseed-50 ring-1 ring-goodseed-100">
                {form.latestWorkImage ? <img src={form.latestWorkImage} alt="รูปงานล่าสุด" className="h-full w-full object-cover" /> : <div className="grid h-full place-items-center text-xs font-bold text-goodseed-500">ยังไม่มีรูป</div>}
              </div>
              <label className="mt-3 flex cursor-pointer items-center justify-center gap-2 rounded-lg bg-white px-3 py-2 text-sm font-black text-goodseed-800 ring-1 ring-goodseed-200">
                <Icon name="upload" className="h-4 w-4" /> แนบรูปงาน
                <input type="file" accept="image/*" className="hidden" onChange={(event) => handleImage("latestWorkImage", event.target.files?.[0])} />
              </label>
            </div>
          </div>

          <div className="grid gap-4 md:grid-cols-2">
            <Input label="ชื่อ-นามสกุล" value={form.name} onChange={(value) => setField("name", value)} />
            <Input label="ชื่อเล่น" value={form.short} onChange={(value) => setField("short", value)} />
            <Input label="เบอร์โทร" value={form.phone} onChange={(value) => setField("phone", value)} />
            <Input label="วันที่เริ่มงาน" value={form.startDate} onChange={(value) => setField("startDate", value)} />
            <Select label="แผนก" value={form.department} onChange={(value) => setField("department", value)} options={["Field Management", "Farm Worker", "Report & Stock", "Maintenance", "Finance", "HR", "อื่น ๆ"]} />
            <Select label="ตำแหน่ง" value={form.position} onChange={(value) => setField("position", value)} options={["ผู้จัดการแปลง", "หัวหน้าคนงาน", "คนงานดูแลแปลง", "คนงานรดน้ำ", "ผู้ช่วยบันทึกรายงาน", "ช่างซ่อมบำรุง", "อื่น ๆ"]} />
            <Select label="สถานะออนไลน์" value={form.status} onChange={(value) => setField("status", value)} options={["Online", "Working", "In Field", "Problem", "Offline"]} />
            <Select label="สถานะพนักงาน" value={form.hrStatus} onChange={(value) => setField("hrStatus", value)} options={["ทำงานอยู่", "ทดลองงาน", "พักงาน", "ลาออก", "ปิดการใช้งาน"]} />
            <Input label="พื้นที่รับผิดชอบ / แปลง" value={form.plot} onChange={(value) => setField("plot", value)} />
            <Input label="จำนวนต้นไม้ที่ดูแล" type="number" value={form.trees} onChange={(value) => setField("trees", value)} />
            <Input label="จำนวนคนงานในทีม" type="number" value={form.team} onChange={(value) => setField("team", value)} />
            <Input label="KPI ล่าสุด (%)" type="number" value={form.kpi} onChange={(value) => setField("kpi", value)} />
            <Select label="สิทธิ์การใช้งานระบบ" value={form.role} onChange={(value) => setField("role", value)} options={["Owner", "Admin", "Manager", "Admin / Manager", "Staff", "Customer"]} />
            <Input label="สวัสดิการที่ได้รับ" value={form.welfare} onChange={(value) => setField("welfare", value)} />
            <Input label="แจ้งเตือนในการ์ด (คั่นด้วย ,)" value={form.alertsText} onChange={(value) => setField("alertsText", value)} />
            <Input label="สถานะครอบครัว" value={form.familyStatus} onChange={(value) => setField("familyStatus", value)} />
            <Input label="จำนวนบุตร" type="number" value={form.children} onChange={(value) => setField("children", value)} />
            <Input label="ผู้ติดต่อฉุกเฉิน" value={form.emergency} onChange={(value) => setField("emergency", value)} />
            <Input label="ทุนการศึกษา / สวัสดิการครอบครัว" value={form.education} onChange={(value) => setField("education", value)} />
            <Input label="กิจกรรมครอบครัว / CSR" value={form.familyActivity} onChange={(value) => setField("familyActivity", value)} />
            <Textarea label="หมายเหตุเพิ่มเติม" value={form.note} onChange={(value) => setField("note", value)} wide />
          </div>
        </div>

        <div className="flex flex-wrap justify-end gap-3 border-t border-goodseed-100 p-5">
          <button onClick={onClose} className="rounded-lg bg-slate-100 px-5 py-3 text-sm font-black text-slate-700">ยกเลิก</button>
          <button onClick={handleSave} className="rounded-lg bg-goodseed-700 px-5 py-3 text-sm font-black text-white shadow-sm">บันทึกข้อมูล</button>
        </div>
      </div>
    </div>
  );
}

function AttendanceRecordModal({ mode, initialRecord, peopleRecords, onClose, onSave }) {
  const [form, setForm] = useState(() => ({
    id: initialRecord?.id || `ATT-${Date.now()}`,
    date: initialRecord?.date || "28 พ.ค. 2569",
    name: initialRecord?.name || peopleRecords[0]?.name || "",
    position: initialRecord?.position || peopleRecords[0]?.position || "",
    shift: initialRecord?.shift || "เช้า",
    time: initialRecord?.time || "08:00 - 17:00",
    area: initialRecord?.area || "แปลง A",
    status: initialRecord?.status || "มาทำงาน",
    note: initialRecord?.note || "",
    photo: initialRecord?.photo || "",
  }));
  const setField = (key, value) => setForm((current) => ({ ...current, [key]: value }));
  const handleImage = async (file) => {
    if (!file) return;
    setField("photo", await readImageFile(file));
  };
  return (
    <div className="fixed inset-0 z-[95] grid place-items-center bg-goodseed-950/50 p-4 backdrop-blur-sm">
      <div className="w-full max-w-3xl rounded-2xl bg-white shadow-2xl">
        <div className="flex items-start justify-between gap-4 border-b border-goodseed-100 p-5">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.18em] text-goodseed-500">Attendance</p>
            <h3 className="text-2xl font-black text-goodseed-950">{mode === "edit" ? "แก้ไขตารางเวร / Attendance" : "เพิ่มตารางเวร / Attendance"}</h3>
          </div>
          <button onClick={onClose} className="rounded-lg bg-goodseed-50 p-2 text-goodseed-800 ring-1 ring-goodseed-100"><Icon name="x" /></button>
        </div>
        <div className="grid gap-4 p-5 md:grid-cols-2">
          <Input label="วันที่" value={form.date} onChange={(value) => setField("date", value)} />
          <Select label="ชื่อผู้รับผิดชอบ" value={form.name} onChange={(value) => {
            const employee = peopleRecords.find((item) => item.name === value);
            setForm((current) => ({ ...current, name: value, position: employee?.position || current.position, area: employee?.plot || current.area }));
          }} options={peopleRecords.map((item) => item.name)} />
          <Input label="ตำแหน่ง" value={form.position} onChange={(value) => setField("position", value)} />
          <Select label="ช่วงเวลา / เวร" value={form.shift} onChange={(value) => setField("shift", value)} options={["เช้า", "บ่าย", "เต็มวัน", "เวรพิเศษ", "วันหยุด"]} />
          <Input label="เวลา" value={form.time} onChange={(value) => setField("time", value)} />
          <Input label="พื้นที่ / แปลง" value={form.area} onChange={(value) => setField("area", value)} />
          <Select label="สถานะ" value={form.status} onChange={(value) => setField("status", value)} options={["มาทำงาน", "ทำงานภาคสนาม", "รอส่งรายงาน", "ลา", "ขาดงาน", "มีปัญหา"]} />
          <label className="rounded-lg border-2 border-dashed border-goodseed-200 bg-goodseed-50 p-4">
            <span className="flex items-center gap-2 text-sm font-bold text-goodseed-800"><Icon name="upload" className="h-4 w-4" />แนบรูปภาพหลักฐาน</span>
            <input type="file" accept="image/*" className="mt-3 w-full text-sm" onChange={(event) => handleImage(event.target.files?.[0])} />
          </label>
          {form.photo && <img src={form.photo} alt="หลักฐาน Attendance" className="h-36 w-full rounded-lg object-cover ring-1 ring-goodseed-100 md:col-span-2" />}
          <Textarea label="หมายเหตุ" value={form.note} onChange={(value) => setField("note", value)} wide />
        </div>
        <div className="flex flex-wrap justify-end gap-3 border-t border-goodseed-100 p-5">
          <button onClick={onClose} className="rounded-lg bg-slate-100 px-5 py-3 text-sm font-black text-slate-700">ยกเลิก</button>
          <button onClick={() => onSave({ ...form, updatedAt: new Date().toLocaleString("th-TH") })} className="rounded-lg bg-goodseed-700 px-5 py-3 text-sm font-black text-white shadow-sm">บันทึกตารางเวร</button>
        </div>
      </div>
    </div>
  );
}

function PeopleOrgChart({ people, onOpen, onEdit, canManage }) {
  const groups = [
    { title: "Owner / Admin", matcher: (item) => ["Owner", "Admin"].includes(item.role), tone: "bg-goodseed-700 text-white" },
    { title: "ผู้จัดการแปลง", matcher: (item) => (item.position || "").includes("ผู้จัดการ") || (item.position || "").includes("หัวหน้า"), tone: "bg-goodseed-100 text-goodseed-900" },
    { title: "คนงานฟาร์ม", matcher: (item) => item.department === "Farm Worker" || (item.position || "").includes("คนงาน"), tone: "bg-amber-100 text-amber-900" },
    { title: "Support / Maintenance", matcher: (item) => !["Owner", "Admin"].includes(item.role) && !(item.department || "").includes("Farm Worker") && !(item.position || "").includes("ผู้จัดการ") && !(item.position || "").includes("หัวหน้า"), tone: "bg-sky-100 text-sky-900" },
  ];
  return (
    <div className="grid gap-4 xl:grid-cols-4">
      {groups.map((group) => {
        const members = people.filter(group.matcher);
        return (
          <div key={group.title} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft">
            <div className={`rounded-lg px-4 py-3 text-center text-sm font-black ${group.tone}`}>{group.title}</div>
            <div className="mt-4 space-y-3">
              {members.map((employee) => (
                <button key={`${group.title}-${employee.id}`} onClick={() => onOpen(employee)} className="w-full rounded-lg border border-goodseed-100 bg-goodseed-50 p-3 text-left transition hover:border-goodseed-300 hover:bg-white">
                  <div className="flex items-center gap-3">
                    <EmployeeAvatar employee={employee} />
                    <div className="min-w-0 flex-1">
                      <p className="truncate font-black text-goodseed-950">{employee.name}</p>
                      <p className="text-xs font-bold text-goodseed-600">{employee.position}</p>
                      <p className="text-xs font-bold text-goodseed-500">{employee.plot}</p>
                    </div>
                  </div>
                  {canManage && <span onClick={(event) => { event.stopPropagation(); onEdit(employee); }} className="mt-3 inline-flex rounded-lg bg-white px-3 py-1.5 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100">แก้ไขข้อมูล</span>}
                </button>
              ))}
              {!members.length && <p className="rounded-lg bg-slate-50 p-3 text-center text-sm font-bold text-slate-500">ยังไม่มีข้อมูลในกลุ่มนี้</p>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function PeopleAttendanceWorkspace({ records, canManage, onAdd, onEdit, onDelete }) {
  return (
    <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-5">
      <SectionHeader
        title="ตารางเวร / Attendance"
        subtitle="บันทึกเวลา พื้นที่รับผิดชอบ สถานะงาน และแนบรูปภาพหลักฐานได้"
        action={canManage ? <button onClick={onAdd} className="rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-black text-white">+ เพิ่มตารางเวร</button> : <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">View Only</Badge>}
      />
      <div className="hidden overflow-x-auto rounded-lg border border-goodseed-100 lg:block">
        <table className="min-w-full divide-y divide-goodseed-100 text-sm">
          <thead className="bg-goodseed-50 text-left text-xs font-black text-goodseed-800">
            <tr>{["วันที่", "ผู้รับผิดชอบ", "ตำแหน่ง", "ช่วงเวลา", "พื้นที่", "สถานะ", "รูป", "หมายเหตุ", "จัดการ"].map((head) => <th key={head} className="px-4 py-3">{head}</th>)}</tr>
          </thead>
          <tbody className="divide-y divide-goodseed-100">
            {records.map((item) => (
              <tr key={item.id} className="align-middle">
                <td className="px-4 py-3 font-bold text-goodseed-900">{item.date}</td>
                <td className="px-4 py-3 font-black text-goodseed-950">{item.name}</td>
                <td className="px-4 py-3 font-bold text-goodseed-700">{item.position}</td>
                <td className="px-4 py-3 font-bold text-goodseed-700">{item.shift} / {item.time}</td>
                <td className="px-4 py-3 font-bold text-goodseed-700">{item.area}</td>
                <td className="px-4 py-3"><Badge className={item.status.includes("ขาด") || item.status.includes("ปัญหา") ? "bg-red-50 text-red-700 ring-red-100" : "bg-goodseed-100 text-goodseed-800 ring-goodseed-200"}>{item.status}</Badge></td>
                <td className="px-4 py-3">{item.photo ? <img src={item.photo} alt={item.name} className="h-12 w-16 rounded-lg object-cover" /> : "-"}</td>
                <td className="max-w-xs px-4 py-3 font-semibold text-goodseed-700">{item.note}</td>
                <td className="px-4 py-3">
                  {canManage ? <div className="flex gap-2"><button onClick={() => onEdit(item)} className="rounded-lg bg-white px-3 py-2 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100">แก้ไข</button><button onClick={() => onDelete(item)} className="rounded-lg bg-red-50 px-3 py-2 text-xs font-black text-red-700 ring-1 ring-red-100">ลบ</button></div> : "-"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="grid gap-3 lg:hidden">
        {records.map((item) => (
          <article key={item.id} className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
            <div className="flex gap-3">
              {item.photo && <img src={item.photo} alt={item.name} className="h-16 w-20 rounded-lg object-cover" />}
              <div className="min-w-0 flex-1">
                <p className="font-black text-goodseed-950">{item.name}</p>
                <p className="text-sm font-bold text-goodseed-700">{item.date} / {item.time}</p>
                <p className="text-sm font-bold text-goodseed-600">{item.area}</p>
              </div>
            </div>
            <p className="mt-3 text-sm font-semibold text-goodseed-700">{item.note}</p>
            {canManage && <div className="mt-3 grid grid-cols-2 gap-2"><button onClick={() => onEdit(item)} className="rounded-lg bg-white px-3 py-2 text-sm font-black text-goodseed-800 ring-1 ring-goodseed-100">แก้ไข</button><button onClick={() => onDelete(item)} className="rounded-lg bg-red-50 px-3 py-2 text-sm font-black text-red-700 ring-1 ring-red-100">ลบ</button></div>}
          </article>
        ))}
      </div>
    </div>
  );
}

function PeopleHrPage({ role, viewMode, initialTab = "Dashboard บุคลากร", planningInitialTab = "kpi" }) {
  const [activeTab, setActiveTab] = useState(initialTab);
  const [peopleRecords, setPeopleRecords] = useState(() => readPeopleHrRecords());
  const [attendanceRecords, setAttendanceRecords] = useState(() => readPeopleHrAttendanceRecords());
  const [query, setQuery] = useState("");
  const [department, setDepartment] = useState("ทั้งหมด");
  const [position, setPosition] = useState("ทั้งหมด");
  const [status, setStatus] = useState("ทั้งหมด");
  const [kpi, setKpi] = useState("ทั้งหมด");
  const [plot, setPlot] = useState("ทั้งหมด");
  const [workState, setWorkState] = useState("ทั้งหมด");
  const [accessRole, setAccessRole] = useState("ทั้งหมด");
  const [selectedEmployee, setSelectedEmployee] = useState(null);
  const [peopleModal, setPeopleModal] = useState(null);
  const [attendanceModal, setAttendanceModal] = useState(null);
  const canManagePeople = ["owner", "admin", "manager"].includes(role);
  const visiblePeople = role === "staff" ? peopleRecords.filter((employee) => employee.name.includes("สมชาย")) : ["admin", "manager"].includes(role) ? peopleRecords.filter((employee) => employee.department !== "Finance") : peopleRecords;
  const filteredPeople = visiblePeople.filter((employee) => {
    const q = query.trim().toLowerCase();
    const matchesQuery = !q || [employee.name, employee.position, employee.plot, employee.department].join(" ").toLowerCase().includes(q);
    const matchesDepartment = department === "ทั้งหมด" || employee.department === department;
    const matchesPosition = position === "ทั้งหมด" || employee.position === position;
    const matchesStatus = status === "ทั้งหมด" || employee.status === status;
    const matchesKpi = kpi === "ทั้งหมด" || (kpi === "ต่ำกว่า 75" ? employee.kpi < 75 : employee.kpi >= 75);
    const matchesPlot = plot === "ทั้งหมด" || employee.plot === plot;
    const matchesWorkState = workState === "ทั้งหมด" || employee.status === workState;
    const matchesRole = accessRole === "ทั้งหมด" || employee.role === accessRole;
    return matchesQuery && matchesDepartment && matchesPosition && matchesStatus && matchesKpi && matchesPlot && matchesWorkState && matchesRole;
  });
  const activeFilteredPeople = filteredPeople.filter((employee) => {
    if (activeTab === "ทีมออนไลน์") return ["Online", "Working", "In Field"].includes(employee.status);
    if (activeTab === "ผู้จัดการแปลง") return employee.position.includes("ผู้จัดการ");
    if (activeTab === "คนงาน") return employee.department === "Farm Worker" || employee.position.includes("คนงาน") || employee.position.includes("หัวหน้า");
    return true;
  });
  const onlineCount = visiblePeople.filter((employee) => ["Online", "Working", "In Field"].includes(employee.status)).length;
  const welfareCount = visiblePeople.filter((employee) => employee.welfare).length;
  const unique = (key) => ["ทั้งหมด", ...Array.from(new Set(visiblePeople.map((employee) => employee[key]))).filter(Boolean)];

  const savePeopleRecord = (record) => {
    setPeopleRecords((current) => {
      const exists = current.some((item) => item.id === record.id);
      const next = exists ? current.map((item) => item.id === record.id ? record : item) : [record, ...current];
      writePeopleHrRecords(next);
      return next;
    });
    setSelectedEmployee(record);
    setPeopleModal(null);
  };

  const archivePeopleRecord = (employee) => {
    if (!window.confirm(`ปิดการใช้งาน ${employee.name}?`)) return;
    setPeopleRecords((current) => {
      const next = current.map((item) => item.id === employee.id ? {
        ...item,
        status: "Offline",
        hrStatus: "ปิดการใช้งาน",
        alerts: Array.from(new Set([...(item.alerts || []), "ปิดการใช้งาน"])),
        updatedAt: new Date().toLocaleString("th-TH"),
      } : item);
      writePeopleHrRecords(next);
      return next;
    });
    if (selectedEmployee?.id === employee.id) setSelectedEmployee(null);
  };

  const saveAttendanceRecord = (record) => {
    setAttendanceRecords((current) => {
      const exists = current.some((item) => item.id === record.id);
      const next = exists ? current.map((item) => item.id === record.id ? record : item) : [record, ...current];
      writePeopleHrAttendanceRecords(next);
      return next;
    });
    setAttendanceModal(null);
  };

  const deleteAttendanceRecord = (record) => {
    if (!window.confirm(`ลบรายการตารางเวรของ ${record.name}?`)) return;
    setAttendanceRecords((current) => {
      const next = current.filter((item) => item.id !== record.id);
      writePeopleHrAttendanceRecords(next);
      return next;
    });
  };

  useEffect(() => {
    setActiveTab(initialTab);
  }, [initialTab]);

  return (
    <section id="people-hr" className="space-y-5">
      <EmployeeSlidePanel employee={selectedEmployee} onClose={() => setSelectedEmployee(null)} onEdit={(employee) => setPeopleModal({ mode: "edit", record: employee })} canManage={canManagePeople} />
      {peopleModal && (
        <PeopleRecordModal
          mode={peopleModal.mode}
          initialRecord={peopleModal.record}
          onClose={() => setPeopleModal(null)}
          onSave={savePeopleRecord}
        />
      )}
      {attendanceModal && (
        <AttendanceRecordModal
          mode={attendanceModal.mode}
          initialRecord={attendanceModal.record}
          peopleRecords={peopleRecords}
          onClose={() => setAttendanceModal(null)}
          onSave={saveAttendanceRecord}
        />
      )}
      <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
        <SectionHeader
          title={<BiLabel th="People / HR" en="Smart Workforce Dashboard" />}
          subtitle="ดูคน ดูงาน ดู KPI ดูสถานะ ดูสวัสดิการ และดูปัญหาทีมงานจากจุดเดียว แยกชัดจาก Dashboard งานฟาร์มหลัก"
          action={
            <div className="flex flex-wrap items-center justify-end gap-2">
              <Badge className={roleInfo(role).badge}>{roleInfo(role).label}</Badge>
              {canManagePeople && <button onClick={() => setPeopleModal({ mode: "add", record: null })} className="rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-black text-white shadow-sm transition hover:bg-goodseed-800">+ เพิ่มข้อมูล</button>}
            </div>
          }
        />
        <div className="thin-scrollbar flex gap-2 overflow-x-auto pb-2">
          {peopleHrTabs.map((tab) => (
            <button key={tab} onClick={() => setActiveTab(tab)} className={`shrink-0 rounded-lg px-4 py-2 text-sm font-black ring-1 transition ${activeTab === tab ? "bg-goodseed-700 text-white ring-goodseed-700" : "bg-white text-goodseed-800 ring-goodseed-100 hover:bg-goodseed-50"}`}>{tab}</button>
          ))}
        </div>
      </div>

      <CrudGovernanceBar role={role} moduleId="employees" title="Employees / พนักงาน CRUD" />

      {activeTab === "KPI / Performance" ? (
        <section className="space-y-5">
          <SectionHeader title="KPI / Performance" subtitle="สรุปคะแนนการทำงานและประสิทธิภาพทีมงาน แยกจาก Farm Work Planning ที่ย้ายไปอยู่ใน Daily Report แล้ว" />
          <KpiDashboardView />
        </section>
      ) : (
        <>

      <div className={`grid gap-3 ${viewMode === "mobile" ? "grid-cols-1" : viewMode === "tablet" ? "grid-cols-2" : "xl:grid-cols-5"}`}>
        <DashboardCard label="พนักงานทั้งหมด" value={visiblePeople.length} unit="คน" icon="users" tone="bg-goodseed-100 text-goodseed-800" />
        <DashboardCard label="พนักงานออนไลน์" value={onlineCount} unit="คน" icon="leaf" tone="bg-green-100 text-green-800" />
        <DashboardCard label="งานวันนี้" value="31" unit="งาน" icon="check" tone="bg-blue-100 text-blue-700" />
        <DashboardCard label="แจ้งเตือน HR" value={hrNotifications.length} unit="รายการ" icon="bell" tone="bg-red-100 text-red-700" />
        <DashboardCard label="ผู้ได้รับสวัสดิการ" value={welfareCount} unit="คน" icon="money" tone="bg-amber-100 text-amber-800" />
      </div>

      <div className="rounded-lg border border-goodseed-100 bg-white/90 p-4 shadow-soft backdrop-blur">
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          <label className="relative xl:col-span-2">
            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-goodseed-400"><Icon name="users" className="h-4 w-4" /></span>
            <input value={query} onChange={(event) => setQuery(event.target.value)} className="w-full rounded-lg border border-goodseed-100 py-3 pl-10 pr-4 text-sm font-bold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="ค้นหาชื่อ, ตำแหน่ง, แปลง, แผนก..." />
          </label>
          <Select label="แผนก" value={department} onChange={setDepartment} options={unique("department")} />
          <Select label="ตำแหน่ง" value={position} onChange={setPosition} options={unique("position")} />
          <Select label="สถานะออนไลน์" value={status} onChange={setStatus} options={["ทั้งหมด", "Online", "Working", "In Field", "Problem", "Offline"]} />
          <Select label="KPI" value={kpi} onChange={setKpi} options={["ทั้งหมด", "75 ขึ้นไป", "ต่ำกว่า 75"]} />
          <Select label="แปลงที่รับผิดชอบ" value={plot} onChange={setPlot} options={unique("plot")} />
          <Select label="สถานะการทำงาน" value={workState} onChange={setWorkState} options={["ทั้งหมด", "Online", "Working", "In Field", "Problem", "Offline"]} />
          <Select label="สิทธิ์การเข้าถึง" value={accessRole} onChange={setAccessRole} options={["ทั้งหมด", "Owner", "Admin", "Manager", "Staff"]} />
        </div>
      </div>

      {activeTab === "ผังองค์กร" ? (
        <PeopleOrgChart people={activeFilteredPeople} onOpen={setSelectedEmployee} onEdit={(employee) => setPeopleModal({ mode: "edit", record: employee })} canManage={canManagePeople} />
      ) : activeTab === "ตารางเวร / Attendance" ? (
        <PeopleAttendanceWorkspace
          records={attendanceRecords}
          canManage={canManagePeople}
          onAdd={() => setAttendanceModal({ mode: "add", record: null })}
          onEdit={(record) => setAttendanceModal({ mode: "edit", record })}
          onDelete={deleteAttendanceRecord}
        />
      ) : activeTab === "Welfare & Family" ? (
        <div className="grid gap-5 xl:grid-cols-3">
          <DashboardPanel title="ข้อมูลสวัสดิการ">
            {["ประกันสังคม", "วันลาพักร้อน", "วันลาป่วย", "ค่าเดินทาง", "ค่า OT", "โบนัส", "ยูนิฟอร์ม"].map((item) => <div key={item} className="mb-3 rounded-lg bg-goodseed-50 p-3 font-black text-goodseed-800">{item}</div>)}
          </DashboardPanel>
          <DashboardPanel title="Family Information">
            {["สถานะครอบครัว", "จำนวนบุตร", "ข้อมูลผู้ติดต่อฉุกเฉิน", "ทุนการศึกษา", "กิจกรรมครอบครัว"].map((item) => <div key={item} className="mb-3 rounded-lg bg-amber-50 p-3 font-black text-amber-800">{item}</div>)}
          </DashboardPanel>
          <DashboardPanel title="CSR / Organization Relation">
            {["กิจกรรมช่วยเหลือพนักงาน", "กิจกรรมฟาร์ม", "การอบรม", "ความสัมพันธ์องค์กร"].map((item) => <div key={item} className="mb-3 rounded-lg bg-sky-50 p-3 font-black text-sky-800">{item}</div>)}
          </DashboardPanel>
        </div>
      ) : (
        <div className={`grid gap-5 ${viewMode === "desktop" ? "xl:grid-cols-[1fr_340px]" : "grid-cols-1"}`}>
          <div className={`grid gap-4 ${viewMode === "mobile" ? "grid-cols-1" : viewMode === "tablet" ? "grid-cols-2" : "xl:grid-cols-2 2xl:grid-cols-3"}`}>
            {activeFilteredPeople.map((employee) => (
              <EmployeeCard
                key={employee.id}
                employee={employee}
                onOpen={setSelectedEmployee}
                onEdit={(employeeRecord) => setPeopleModal({ mode: "edit", record: employeeRecord })}
                onArchive={archivePeopleRecord}
                canManage={canManagePeople}
              />
            ))}
          </div>
          <aside className="space-y-5">
            <DashboardPanel title="Notification Panel สำหรับ HR" action={<Badge className="bg-red-50 text-red-700 ring-red-100">{hrNotifications.length} รายการ</Badge>}>
              <div className="space-y-3">
                {hrNotifications.map((item) => (
                  <button key={item.title} className={`w-full rounded-lg p-3 text-left ring-1 ring-goodseed-100 ${item.tone}`}>
                    <p className="font-black">{item.title}</p>
                    <p className="mt-1 text-xs font-bold opacity-80">{item.detail}</p>
                  </button>
                ))}
              </div>
            </DashboardPanel>
            <DashboardPanel title="ภาพรวมสิทธิ์การเข้าถึง">
              <div className="space-y-3">
                {["Owner เห็นข้อมูลทั้งหมด", "Admin จัดการระบบทั้งหมด", "Manager เห็นเฉพาะทีมและแปลงที่รับผิดชอบ", "Staff เห็นเฉพาะข้อมูลของตนเองและงานที่ได้รับมอบหมาย"].map((item) => <div key={item} className="rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800">{item}</div>)}
              </div>
            </DashboardPanel>
          </aside>
        </div>
      )}
        </>
      )}
    </section>
  );
}

function InfoPanel({ id, title, icon, items }) {
  return (
    <div id={id} className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft sm:p-6">
      <div className="flex items-start gap-3">
        <div className="grid h-11 w-11 shrink-0 place-items-center rounded-lg bg-goodseed-100 text-goodseed-800"><Icon name={icon} /></div>
        <h3 className="text-lg font-extrabold leading-snug text-goodseed-900">{title}</h3>
      </div>
      <div className="mt-5 space-y-3">
        {items.map((item) => <div key={item} className="flex items-start gap-3 rounded-lg bg-goodseed-50 px-4 py-3 text-sm font-semibold leading-7 text-goodseed-800"><span className="mt-2 h-2 w-2 shrink-0 rounded-full bg-goodseed-600" /><span className="min-w-0 break-words">{item}</span></div>)}
      </div>
    </div>
  );
}

const workPlanTabs = [
  { id: "yearly", label: "Yearly Plan", th: "แผนรายปี" },
  { id: "monthly", label: "Monthly Plan", th: "แผนรายเดือน" },
  { id: "weekly", label: "Weekly Plan", th: "แผนรายสัปดาห์" },
  { id: "daily", label: "Daily Plan", th: "แผนรายวัน" },
  { id: "hourly", label: "Hourly Tasks", th: "งานรายชั่วโมง" },
  { id: "team", label: "Team Assignment", th: "มอบหมายงาน" },
  { id: "progress", label: "Progress Tracking", th: "ติดตามความคืบหน้า" },
  { id: "kpi", label: "KPI Dashboard", th: "ประเมิน KPI" },
];

const workPlanFilters = [
  ["ปี", "2026"], ["เดือน", "มิถุนายน"], ["สัปดาห์", "Week 2"], ["วันที่", "10 มิ.ย. 2569"], ["ประเภทงาน", "ทั้งหมด"],
  ["แปลง/โซน", "A1-C47"], ["ผู้รับผิดชอบ", "ทุกทีม"], ["สถานะ", "Active"], ["Priority", "High + Medium"], ["KPI Status", "On Track"],
];

const workPlanActions = [
  ["Add Task", "plus"], ["Edit Task", "edit"], ["Assign Team", "users"], ["Update Progress", "check"], ["Upload Evidence", "upload"],
  ["Complete Task", "check"], ["Approve Task", "shield"], ["Export PDF", "download"], ["Sync Google Calendar", "calendar"], ["Generate KPI Report", "file"],
];

const workPlanCategoryClasses = {
  plant: "border-goodseed-200 bg-goodseed-50 text-goodseed-900",
  inspect: "border-sky-200 bg-sky-50 text-sky-900",
  inventory: "border-orange-200 bg-orange-50 text-orange-900",
  meeting: "border-violet-200 bg-violet-50 text-violet-900",
  urgent: "border-red-200 bg-red-50 text-red-900",
  holiday: "border-slate-200 bg-slate-50 text-slate-700",
  maintenance: "border-amber-200 bg-amber-50 text-amber-900",
  experiment: "border-lime-200 bg-lime-50 text-lime-900",
};

const yearlyMilestones = [
  { month: "ม.ค.", quarter: "Q1", title: "Kickoff รอบปลูก A-B", detail: "ตั้งเป้า 3,354 ต้น ตรวจผังแปลงและระบบน้ำ", progress: 82, kpi: "ต้นไม้ตั้งตัว 94%" },
  { month: "ก.พ.", quarter: "Q1", title: "ขยายแปลง C", detail: "เพิ่มจุดตรวจ QR และวางแผนแรงงานรายฤดูกาล", progress: 76, kpi: "QR Ready 88%" },
  { month: "มี.ค.", quarter: "Q1", title: "ทดลอง GS-03", detail: "สูตรปุ๋ยชีวภาพ + ไบโอชาร์แปลงทดลอง", progress: 70, kpi: "Experiment 7 ชุด" },
  { month: "เม.ย.", quarter: "Q2", title: "CAPEX ระบบน้ำ", detail: "ปรับปั๊มน้ำ วาล์ว และเส้นทางรถ", progress: 64, kpi: "PM Pass 91%" },
  { month: "พ.ค.", quarter: "Q2", title: "ตรวจแปลงเข้มข้น", detail: "ตรวจโรคแมลงและเตรียมแผนเดือนมิถุนายน", progress: 86, kpi: "Inspection 128 แถว" },
  { month: "มิ.ย.", quarter: "Q2", title: "Weekly Farm Plan", detail: "ตารางงานรายสัปดาห์ตามไฟล์ตัวอย่าง ปลูก-ตรวจ-สรุป", progress: 58, kpi: "On-time 89%" },
  { month: "ก.ค.", quarter: "Q3", title: "ขยายรอบปลูก D", detail: "จัดซื้อวัสดุคลุมดิน ไม้ค้ำ และทีมปลูกเพิ่ม", progress: 35, kpi: "Budget ใช้ 42%" },
  { month: "ส.ค.", quarter: "Q3", title: "ผลิตไบโอชาร์", detail: "รอบผลิตทดลองและบันทึกต้นทุนต่อกิโลกรัม", progress: 28, kpi: "Biochar 1.2 ตัน" },
  { month: "ก.ย.", quarter: "Q3", title: "KPI Review Q3", detail: "ประชุมเจ้าของฟาร์ม ประเมินทีมและคุณภาพงาน", progress: 22, kpi: "Team score 86" },
  { month: "ต.ค.", quarter: "Q4", title: "ขยายรอบปลูก E", detail: "ปรับแผนแรงงานและจัดซื้อวัสดุรอบปลายปี", progress: 18, kpi: "Labor plan 100%" },
  { month: "พ.ย.", quarter: "Q4", title: "Vision 2030", detail: "ทบทวน Smart Farm Organization และระบบ Traceability", progress: 12, kpi: "Audit ready" },
  { month: "ธ.ค.", quarter: "Q4", title: "Year-end KPI", detail: "สรุป OPEX/CAPEX, KPI รายไตรมาส และแผนปีถัดไป", progress: 8, kpi: "Report complete" },
];

const monthlyWorkItems = [
  { day: 1, type: "holiday", title: "วันหยุดชดเชย / รายการ", team: "Owner", workers: 0, progress: 100, status: "เสร็จแล้ว", kpi: "Attendance", priority: "Low" },
  { day: 3, type: "inspect", title: "วันตรวจรายการ 1 และ 3 มิ.ย.", team: "Manager", workers: 4, progress: 80, status: "กำลังทำ", kpi: "Inspection KPI", priority: "High" },
  { day: 4, type: "inspect", title: "เข้าตรวจฟาร์ม แถว 1-30", team: "Supervisor A", workers: 6, progress: 66, status: "กำลังทำ", kpi: "Quality KPI", priority: "High" },
  { day: 6, type: "maintenance", title: "ซ่อมแซมรั้วและเตรียมงานระบบน้ำ", team: "Maintenance", workers: 5, progress: 42, status: "รอดำเนินการ", kpi: "Maintenance KPI", priority: "Medium" },
  { day: 9, type: "inspect", title: "วันตรวจฟาร์ม 4, 9, 15, 22, 29", team: "Manager", workers: 5, progress: 30, status: "กำลังทำ", kpi: "Inspection KPI", priority: "High" },
  { day: 10, type: "urgent", title: "ปิดงานบ่อบาดาล / ระบบน้ำ", team: "Maintenance", workers: 4, progress: 72, status: "กำลังทำ", kpi: "Maintenance KPI", priority: "Urgent" },
  { day: 12, type: "plant", title: "เริ่มปลูกหว่านและไม้ล้อม", team: "Planting Team", workers: 8, progress: 45, status: "กำลังทำ", kpi: "Productivity KPI", priority: "High" },
  { day: 15, type: "inspect", title: "ตรวจงานใส่ปุ๋ย ไม้ล้อม และรั้วพร้อม", team: "QC Team", workers: 5, progress: 54, status: "กำลังทำ", kpi: "Quality KPI", priority: "High" },
  { day: 17, type: "plant", title: "เชื่อมแนวปลูกรอบคลองกับระบบน้ำ", team: "Planting Team", workers: 7, progress: 38, status: "กำลังทำ", kpi: "Productivity KPI", priority: "Medium" },
  { day: 19, type: "experiment", title: "เก็บงานพื้นที่ทดลองและตรวจแปลงรอบที่ 4", team: "R&D", workers: 3, progress: 61, status: "กำลังทำ", kpi: "Experiment KPI", priority: "Medium" },
  { day: 21, type: "meeting", title: "สรุปงานประจำสัปดาห์", team: "Owner + Manager", workers: 2, progress: 90, status: "เสร็จแล้ว", kpi: "Reporting KPI", priority: "Medium" },
  { day: 22, type: "inspect", title: "ตรวจระบบน้ำและติดตามต้นไม้", team: "Supervisor B", workers: 5, progress: 48, status: "กำลังทำ", kpi: "Inspection KPI", priority: "High" },
  { day: 25, type: "plant", title: "งานแปลงปลูกและพื้นที่รอบสวน", team: "Planting Team", workers: 9, progress: 36, status: "รอดำเนินการ", kpi: "Productivity KPI", priority: "High" },
  { day: 26, type: "meeting", title: "ตรวจภาพรวมงานเดือน", team: "Owner", workers: 2, progress: 40, status: "กำลังทำ", kpi: "Reporting KPI", priority: "Medium" },
  { day: 28, type: "meeting", title: "สรุปผลทดลองและสรุปงานเดือน", team: "Owner + R&D", workers: 4, progress: 20, status: "รอดำเนินการ", kpi: "Experiment KPI", priority: "High" },
  { day: 29, type: "inspect", title: "ตรวจฟาร์มก่อนปิดเดือน", team: "Manager", workers: 4, progress: 25, status: "รอดำเนินการ", kpi: "Quality KPI", priority: "High" },
  { day: 30, type: "inventory", title: "ปิดงานเดือนมิถุนายน / จ่ายเงินเดือน", team: "Admin", workers: 2, progress: 10, status: "รอดำเนินการ", kpi: "Inventory KPI", priority: "Medium" },
];

const weeklyWorkPlan = [
  { day: "จันทร์ 8 มิ.ย.", goal: "จัดการฟาร์มโดยรวมก่อนเริ่มสัปดาห์", tasks: ["ตรวจแปลง A1: 102-121-128", "แผนรอบที่ 2: แถว 1-22", "เตรียมไม้ค้ำโคนต้น A1-36"], zone: "A1 / A2", lead: "คุณหวาน", workers: 6, materials: "ฟอร์มตรวจ, กล้อง, QR Scanner", deadline: "17:00", progress: 64, status: "กำลังทำ", priority: "High", kpi: "Inspection 64%, Report 1/1", type: "inspect" },
  { day: "อังคาร 9 มิ.ย.", goal: "ตรวจฟาร์มสัปดาห์ที่ 2 และวางระบบน้ำ", tasks: ["ตรวจแปลงรอบที่ 2: แถว 23-52", "ตรวจจุดเตรียมวางรอบต้นไม้", "แจ้งรายการวัสดุคลัง"], zone: "A2 / B1", lead: "Supervisor A", workers: 5, materials: "ท่อ PVC, เทปวัด, checklist", deadline: "16:30", progress: 52, status: "กำลังทำ", priority: "High", kpi: "Quality 91%", type: "inspect" },
  { day: "พุธ 10 มิ.ย.", goal: "ปิดงานบ่อบาดาลและเช็กระบบน้ำ", tasks: ["ซ่อมวาล์วหลัก", "ตรวจแปลงรอบที่ 2: แถว 53-82", "เตรียมงานรอบต้นไม้"], zone: "Pump House / A2", lead: "พี่ไกร", workers: 4, materials: "ประแจ, วาล์ว, เครื่องมือช่าง", deadline: "15:00", progress: 72, status: "กำลังทำ", priority: "Urgent", kpi: "Maintenance 72%", type: "maintenance" },
  { day: "พฤหัส 11 มิ.ย.", goal: "เตรียมหลุมปลูกและวัสดุค้ำต้น", tasks: ["ตรวจแปลงรอบที่ 2: แถว 83-112", "ดูแลไม้ค้ำเตรียมใช้", "เบิกปุ๋ยอินทรีย์"], zone: "B1 / คลังวัสดุ", lead: "พี่สมชาย", workers: 7, materials: "จอบ, ปุ๋ย, ไม้ค้ำ, เชือก", deadline: "17:00", progress: 48, status: "รอดำเนินการ", priority: "Medium", kpi: "Inventory 88%", type: "plant" },
  { day: "ศุกร์ 12 มิ.ย.", goal: "เริ่มปลูกหว่านและไม้เสริมรอบแปลง", tasks: ["ตรวจแปลงรอบที่ 2: แถว 113-128", "เตรียมรอบที่ 3: แถว 1-14", "เตรียมวงรอบต้นไม้"], zone: "A3 / B2", lead: "คุณหวาน", workers: 9, materials: "ต้นกล้า, ปุ๋ย, ระบบน้ำสำรอง", deadline: "16:00", progress: 38, status: "กำลังทำ", priority: "High", kpi: "Planting 210 ต้น", type: "plant" },
  { day: "เสาร์ 13 มิ.ย.", goal: "ติดตามงานปลูกรอบคลองและการทดลอง", tasks: ["ตรวจแปลงรอบที่ 3: แถว 15-44", "เตรียมวงรอบต้นไม้ต่อเนื่อง", "เก็บข้อมูล R&D"], zone: "คลอง / R&D", lead: "R&D Team", workers: 6, materials: "กล้อง, ถังน้ำ, biochar", deadline: "16:30", progress: 58, status: "กำลังทำ", priority: "Medium", kpi: "Experiment 7 plots", type: "experiment" },
  { day: "อาทิตย์ 14 มิ.ย.", goal: "สรุปสัปดาห์และส่งรายงานให้ Owner", tasks: ["ตรวจแปลงรอบที่ 3: แถว 45-74", "สรุปภาพหลักฐานบัญชีรายงาน", "เตรียมแผนสัปดาห์ถัดไป"], zone: "Office / A3", lead: "Manager", workers: 3, materials: "รายงาน, รูปภาพ, Google Calendar", deadline: "17:00", progress: 86, status: "เสร็จแล้ว", priority: "Medium", kpi: "Reporting 100%", type: "meeting" },
];

const hourlyTasks = [
  { time: "07:30 - 08:00", task: "ประชุมเช้า / แจกแจงงาน", owner: "คุณหวาน", people: 14, area: "ลานประชุม", tools: "แผนรายวัน, วิทยุ", material: "Checklist", target: "ทีมรับทราบครบ", result: "ทุกคนกดรับทราบงาน", evidence: "รูปประชุม + attendance", kpi: "Reporting KPI" },
  { time: "08:00 - 10:00", task: "เตรียมพื้นที่ / เตรียมอุปกรณ์", owner: "Supervisor A", people: 8, area: "A1-A3", tools: "จอบ, ถังน้ำ, QR", material: "ปุ๋ยอินทรีย์", target: "พร้อมทำงานหลัก", result: "พื้นที่พร้อม 100%", evidence: "รูปก่อนเริ่ม", kpi: "Team Management KPI" },
  { time: "10:00 - 12:00", task: "งานหลักช่วงเช้า", owner: "พี่ไกร", people: 6, area: "A2 / Pump", tools: "เครื่องมือช่าง", material: "วาล์ว, ท่อ", target: "ซ่อมระบบน้ำ", result: "แรงดันน้ำปกติ", evidence: "วิดีโอทดสอบน้ำ", kpi: "Maintenance KPI" },
  { time: "13:00 - 15:00", task: "งานหลักช่วงบ่าย", owner: "Planting Team", people: 9, area: "B1-B2", tools: "จอบ, ไม้ค้ำ", material: "ต้นกล้า, ปุ๋ย", target: "ปลูก 210 ต้น", result: "ต้นไม้ติดป้ายครบ", evidence: "รูปหลังปลูก + QR", kpi: "Productivity KPI" },
  { time: "15:00 - 16:30", task: "ตรวจคุณภาพ / เก็บงาน", owner: "QC Team", people: 4, area: "A1-C47", tools: "Checklist, กล้อง", material: "ป้ายแก้ไข", target: "จุดตรวจผ่าน 95%", result: "รายการแก้ไขไม่เกิน 5 จุด", evidence: "Evidence gallery", kpi: "Quality KPI" },
  { time: "16:30 - 17:00", task: "ส่งรายงาน / รูปภาพ / สรุปปัญหา", owner: "Manager", people: 3, area: "Office", tools: "มือถือ, Dashboard", material: "รายงาน", target: "รายงานครบก่อน 17:00", result: "Owner เห็นข้อมูลทันที", evidence: "Daily Work Report", kpi: "Reporting KPI" },
];

const teamAssignments = [
  { role: "Owner", access: "เห็นทั้งหมด / วางแผนรายปี-เดือน-สัปดาห์ / อนุมัติงาน / ตรวจ KPI", people: "เจ้าของฟาร์ม", scope: "Dashboard ทั้งหมด", status: "อนุมัติ 18 งาน", badge: "bg-goodseed-700 text-white ring-goodseed-700" },
  { role: "Admin / Manager", access: "สร้างและแก้ไขงาน มอบหมายทีม ติดตามงาน สรุปรายงานส่ง Owner", people: "คุณหวาน", scope: "ทุกแปลง + คลัง", status: "กำลังติดตาม 24 งาน", badge: "bg-sky-100 text-sky-800 ring-sky-200" },
  { role: "Supervisor", access: "เห็นงานที่ได้รับ แจกแจงคนงาน อัปเดตสถานะ แนบรูป แจ้งปัญหา", people: "Supervisor A/B", scope: "A1-C47", status: "ภาคสนาม 12 งาน", badge: "bg-amber-100 text-amber-900 ring-amber-200" },
  { role: "Staff / Worker", access: "เห็นเฉพาะงานตัวเอง เวลา สถานที่ เป้าหมาย กดรับทราบ ส่งรูปหรือหมายเหตุ", people: "ทีมปลูก / ทีมรดน้ำ", scope: "งานรายวัน", status: "รับทราบ 31/36 คน", badge: "bg-slate-100 text-slate-700 ring-slate-200" },
];

const progressItems = [
  { task: "ตรวจแปลงประจำวัน 30 แถว / จาก 128 แถว", planned: 78, actual: 72, status: "กำลังทำ", delay: "ล่าช้า 6%", risk: "Medium", approval: "รอ Manager", evidence: ["รูปแปลง 12 รูป", "GPS 6 จุด", "QR Scan 30 รายการ"] },
  { task: "ซ่อมบ่อบาดาลและระบบน้ำ", planned: 80, actual: 72, status: "กำลังทำ", delay: "เสี่ยงล่าช้า", risk: "High", approval: "รอ Owner", evidence: ["วิดีโอทดสอบน้ำ", "รูปอะไหล่", "บันทึกช่าง"] },
  { task: "ปลูกไม้ล้อมรอบใหม่", planned: 45, actual: 38, status: "รอดำเนินการ", delay: "รอวัสดุ", risk: "Medium", approval: "อนุมัติแล้ว", evidence: ["รูปก่อนปลูก", "รายการต้นไม้", "GPS Plot"] },
  { task: "สรุปรายงานประจำสัปดาห์", planned: 100, actual: 100, status: "เสร็จแล้ว", delay: "ตรงเวลา", risk: "Low", approval: "อนุมัติแล้ว", evidence: ["PDF Report", "รูปภาพ 38 รูป", "KPI Summary"] },
];

const kpiCards = [
  { category: "Productivity KPI", value: "210", unit: "ต้น/วัน", detail: "จำนวนต้นไม้ปลูกต่อวัน", progress: 84 },
  { category: "Quality KPI", value: "128", unit: "แถว", detail: "จำนวนแถวที่ตรวจ", progress: 76 },
  { category: "Reporting KPI", value: "96%", unit: "ครบ", detail: "รายงานส่งครบตามเวลา", progress: 96 },
  { category: "Team Management KPI", value: "88", unit: "คะแนน", detail: "ประสิทธิภาพแรงงาน", progress: 88 },
  { category: "Maintenance KPI", value: "91%", unit: "พร้อม", detail: "อุปกรณ์และระบบน้ำพร้อมใช้", progress: 91 },
  { category: "Experiment KPI", value: "7", unit: "ชุด", detail: "งานทดลองที่ติดตามอยู่", progress: 70 },
  { category: "Inventory KPI", value: "93%", unit: "พร้อม", detail: "วัตถุดิบพร้อมใช้งาน", progress: 93 },
];

function MiniProgress({ value, className = "bg-goodseed-600" }) {
  return <div className="h-2.5 overflow-hidden rounded-full bg-slate-100"><div className={`h-full rounded-full ${className}`} style={{ width: `${value}%` }} /></div>;
}

function WorkPlanningFilterBar() {
  return (
    <div className="rounded-lg border border-goodseed-100 bg-white/85 p-3 shadow-soft backdrop-blur">
      <div className="thin-scrollbar flex gap-2 overflow-x-auto pb-1">
        {workPlanFilters.map(([label, value]) => (
          <button key={label} className="min-w-fit rounded-lg border border-goodseed-100 bg-goodseed-50 px-3 py-2 text-left text-xs font-extrabold text-goodseed-800">
            <span className="block text-[10px] text-goodseed-500">{label}</span>{value}
          </button>
        ))}
      </div>
    </div>
  );
}

function WorkPlanningActions() {
  return (
    <div className="thin-scrollbar flex gap-2 overflow-x-auto pb-1">
      {workPlanActions.map(([label, icon], index) => (
        <button key={label} className={`inline-flex min-w-fit items-center gap-2 rounded-lg px-3 py-2 text-xs font-extrabold shadow-sm transition ${index < 4 ? "bg-goodseed-700 text-white" : "border border-goodseed-100 bg-white text-goodseed-800 hover:bg-goodseed-50"}`}>
          <Icon name={icon} className="h-4 w-4" />{label}
        </button>
      ))}
    </div>
  );
}

function YearlyPlanView({ setActiveTab }) {
  const quarters = ["Q1", "Q2", "Q3", "Q4"];
  return (
    <div className="space-y-5">
      <div className="grid gap-3 md:grid-cols-4">
        {[["เป้าหมายต้นไม้ทั้งปี", "6,942 ต้น", "ขยายรอบปลูก A-F"], ["CAPEX / OPEX", "4.8M / 2.1M", "งบระบบน้ำ แรงงาน วัตถุดิบ"], ["Progress รายปี", "58%", "ตามแผนงานเดือนมิถุนายน"], ["Vision 2030", "Smart Farm Org", "QR + KPI + Traceability"]].map(([label, value, detail]) => (
          <div key={label} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft"><p className="text-xs font-extrabold text-goodseed-600">{label}</p><p className="mt-2 text-2xl font-black text-goodseed-950">{value}</p><p className="mt-1 text-xs font-semibold leading-5 text-goodseed-700">{detail}</p></div>
        ))}
      </div>
      <div className="grid gap-4 xl:grid-cols-4">
        {quarters.map((quarter) => (
          <div key={quarter} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft">
            <div className="mb-3 flex items-center justify-between"><h3 className="text-lg font-black text-goodseed-950">{quarter}</h3><Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">KPI Review</Badge></div>
            <div className="space-y-3">
              {yearlyMilestones.filter((item) => item.quarter === quarter).map((item) => (
                <button key={item.month} onClick={() => setActiveTab("monthly")} className="w-full rounded-lg border border-goodseed-100 bg-goodseed-50 p-3 text-left transition hover:border-goodseed-300 hover:bg-white">
                  <div className="flex items-start justify-between gap-3"><div><p className="text-sm font-black text-goodseed-950">{item.month} - {item.title}</p><p className="mt-1 text-xs font-semibold leading-5 text-goodseed-700">{item.detail}</p></div><span className="text-xs font-black text-goodseed-700">{item.progress}%</span></div>
                  <div className="mt-3"><MiniProgress value={item.progress} /></div><p className="mt-2 text-xs font-bold text-goodseed-600">{item.kpi}</p>
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div className="grid gap-4 lg:grid-cols-3">
        {[["Budget Summary", "CAPEX ระบบน้ำ 1.8M / OPEX แรงงาน 820K / วัตถุดิบ 460K"], ["Risk Summary", "ฝนสูงเดือนมิถุนายน, วัสดุคลุมดินเหลือ 18 ม้วน, ระบบน้ำต้อง PM"], ["Quarterly Meeting", "Q2 review: 28 มิ.ย. | Q3 review: 29 ก.ย. | Year-end KPI: 20 ธ.ค."]].map(([title, detail]) => <div key={title} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft"><h3 className="font-black text-goodseed-950">{title}</h3><p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{detail}</p></div>)}
      </div>
    </div>
  );
}

function MonthlyPlanView({ setActiveTab }) {
  const days = getCalendarDays(2026, 5);
  return (
    <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft">
      <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
        <div><h3 className="text-xl font-black text-goodseed-950">June 2026 / ปฏิทินงานรายเดือน</h3><p className="text-sm font-semibold text-goodseed-700">กดแต่ละวันเพื่อเปิด Daily Plan ของวันนั้น</p></div>
        <div className="flex flex-wrap gap-2 text-xs font-bold">
          {[["งานปลูก/ดูแล", "bg-goodseed-500"], ["ตรวจแปลง", "bg-sky-500"], ["คลังสินค้า", "bg-orange-500"], ["ประชุม", "bg-violet-500"], ["เร่งด่วน", "bg-red-500"], ["วันหยุด", "bg-slate-400"]].map(([label, color]) => <span key={label} className="rounded-full bg-white px-2 py-1 ring-1 ring-goodseed-100"><i className={`mr-1.5 inline-block h-2.5 w-2.5 rounded-full ${color}`} />{label}</span>)}
        </div>
      </div>
      <div className="grid grid-cols-7 gap-2 text-center text-xs font-black text-goodseed-700">{weekDays.map((day) => <span key={day} className="rounded-md bg-goodseed-50 py-2">{day}</span>)}</div>
      <div className="mt-2 grid grid-cols-1 gap-2 sm:grid-cols-7">
        {days.map((day, index) => {
          const item = monthlyWorkItems.find((work) => work.day === day);
          return (
            <button key={`${day || "empty"}-${index}`} onClick={() => item && setActiveTab("daily")} className={`min-h-[138px] rounded-lg border p-2 text-left transition ${item ? workPlanCategoryClasses[item.type] : "border-goodseed-50 bg-white text-slate-300"} ${item ? "hover:-translate-y-0.5 hover:shadow-soft" : ""}`}>
              {day && <p className="text-sm font-black">{day}</p>}
              {item && <div className="mt-2 space-y-2"><p className="line-clamp-2 text-xs font-black leading-5">{item.title}</p><div className="flex flex-wrap gap-1"><Badge className="bg-white/80 text-goodseed-800 ring-white">{item.priority}</Badge><StatusBadge status={item.status} /></div><p className="text-[11px] font-bold leading-4">{item.team} / {item.workers} คน</p><MiniProgress value={item.progress} className={item.type === "urgent" ? "bg-red-500" : item.type === "inspect" ? "bg-sky-500" : "bg-goodseed-600"} /><p className="text-[11px] font-extrabold">{item.kpi}</p></div>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function WeeklyPlanView({ setActiveTab }) {
  return (
    <div className="space-y-4">
      <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft"><h3 className="text-xl font-black text-goodseed-950">ตารางงานฟาร์มรายสัปดาห์ เดือนมิถุนายน 2026</h3><p className="mt-1 text-sm font-semibold text-goodseed-700">ปรับจากรูปแบบตารางตัวอย่างให้เป็น card per day พร้อม progress, status, priority และ KPI mini summary</p></div>
      <div className="grid gap-4 lg:grid-cols-2 2xl:grid-cols-4">
        {weeklyWorkPlan.map((day) => (
          <article key={day.day} className={`rounded-lg border p-4 shadow-soft ${workPlanCategoryClasses[day.type]}`}>
            <div className="flex items-start justify-between gap-3"><div><h3 className="text-lg font-black">{day.day}</h3><p className="mt-1 text-sm font-bold leading-6">{day.goal}</p></div><Badge className={`${day.priority === "Urgent" ? "bg-red-600 text-white ring-red-600" : day.priority === "High" ? "bg-goodseed-700 text-white ring-goodseed-700" : "bg-white text-goodseed-800 ring-white"}`}>{day.priority}</Badge></div>
            <ul className="mt-4 space-y-2 text-sm font-semibold leading-6">{day.tasks.map((task) => <li key={task}>- {task}</li>)}</ul>
            <div className="mt-4 grid grid-cols-2 gap-2 text-xs font-bold"><span className="rounded-md bg-white/75 p-2">แปลง/โซน<br />{day.zone}</span><span className="rounded-md bg-white/75 p-2">ผู้รับผิดชอบ<br />{day.lead}</span><span className="rounded-md bg-white/75 p-2">คนงาน<br />{day.workers} คน</span><span className="rounded-md bg-white/75 p-2">Deadline<br />{day.deadline}</span></div>
            <p className="mt-3 rounded-md bg-white/75 p-2 text-xs font-bold leading-5">วัสดุ/อุปกรณ์: {day.materials}</p>
            <div className="mt-4"><div className="mb-2 flex justify-between text-xs font-black"><span>Progress</span><span>{day.progress}%</span></div><MiniProgress value={day.progress} className={day.type === "inspect" ? "bg-sky-500" : day.type === "maintenance" ? "bg-amber-500" : "bg-goodseed-600"} /></div>
            <div className="mt-4 flex flex-wrap items-center justify-between gap-2"><StatusBadge status={day.status} /><span className="text-xs font-black">{day.kpi}</span><button onClick={() => setActiveTab("daily")} className="rounded-lg bg-white px-3 py-2 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100">ดูรายละเอียดรายวัน</button></div>
          </article>
        ))}
      </div>
    </div>
  );
}

function DailyPlanView() {
  return (
    <div className="grid gap-4 xl:grid-cols-[0.8fr_1.2fr]">
      <div className="space-y-4">
        <div className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft"><Badge className="bg-goodseed-700 text-white ring-goodseed-700">10 มิ.ย. 2569</Badge><h3 className="mt-3 text-2xl font-black text-goodseed-950">เป้าหมายของวัน: ปิดงานระบบน้ำและเตรียมปลูกรอบใหม่</h3><div className="mt-4 grid gap-2 text-sm font-bold text-goodseed-800"><span className="rounded-lg bg-goodseed-50 p-3">สภาพอากาศ: 32°C มีเมฆบางส่วน ฝน 35%</span><span className="rounded-lg bg-goodseed-50 p-3">Manager in charge: คุณหวาน</span><span className="rounded-lg bg-goodseed-50 p-3">หมายเหตุ Owner: งานระบบน้ำต้องมีวิดีโอทดสอบก่อนอนุมัติ</span></div></div>
        <div className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft"><h3 className="font-black text-goodseed-950">จุดตรวจคุณภาพและหลักฐาน</h3><div className="mt-3 grid gap-2">{["รูปก่อนเริ่มงาน", "GPS Location ทุกโซน", "QR Verification ต้นไม้/แปลง", "วิดีโอระบบน้ำ", "รูปหลังจบงาน", "Daily Work Report"].map((item) => <label key={item} className="flex items-center gap-3 rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800"><input type="checkbox" defaultChecked={item.includes("รูป")} className="h-4 w-4 accent-goodseed-700" />{item}</label>)}</div></div>
      </div>
      <div className="space-y-3">
        {weeklyWorkPlan.slice(1, 5).map((item) => (
          <article key={item.day} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft">
            <div className="flex flex-wrap items-start justify-between gap-3"><div><h3 className="text-lg font-black text-goodseed-950">{item.goal}</h3><p className="mt-1 text-sm font-bold text-goodseed-700">{item.zone} / {item.lead} / ทีม {item.workers} คน</p></div><StatusBadge status={item.status} /></div>
            <div className="mt-3 grid gap-3 lg:grid-cols-3"><div className="rounded-lg bg-goodseed-50 p-3"><p className="text-xs font-black text-goodseed-600">เครื่องมือ</p><p className="mt-1 text-sm font-bold text-goodseed-900">{item.materials}</p></div><div className="rounded-lg bg-goodseed-50 p-3"><p className="text-xs font-black text-goodseed-600">วัตถุดิบ</p><p className="mt-1 text-sm font-bold text-goodseed-900">ปุ๋ยอินทรีย์, ไม้ค้ำ, น้ำสำรอง</p></div><div className="rounded-lg bg-goodseed-50 p-3"><p className="text-xs font-black text-goodseed-600">KPI</p><p className="mt-1 text-sm font-bold text-goodseed-900">{item.kpi}</p></div></div>
            <div className="mt-3 rounded-lg bg-slate-50 p-3 text-sm font-semibold leading-7 text-slate-700">ขั้นตอน: ตรวจพื้นที่ - แจกแจงทีม - ทำงานตามแถว - QC จุดเสี่ยง - ถ่ายหลักฐาน - อัปเดตสถานะในระบบ</div><div className="mt-3"><MiniProgress value={item.progress} /></div>
          </article>
        ))}
      </div>
    </div>
  );
}

function HourlyTasksView() {
  return (
    <div className="thin-scrollbar overflow-x-auto rounded-lg border border-goodseed-100 bg-white shadow-soft">
      <table className="min-w-[1180px] w-full text-left text-sm"><thead className="bg-goodseed-50 text-goodseed-800"><tr>{["เวลา", "งานที่ต้องทำ", "ผู้รับผิดชอบ", "คน", "พื้นที่", "เครื่องมือ", "วัตถุดิบ", "เป้าหมาย", "ผลลัพธ์", "หลักฐาน", "KPI Relation"].map((head) => <th key={head} className="px-3 py-3 font-black">{head}</th>)}</tr></thead><tbody className="divide-y divide-goodseed-100">{hourlyTasks.map((row) => <tr key={row.time} className="align-top">{[row.time, row.task, row.owner, row.people, row.area, row.tools, row.material, row.target, row.result, row.evidence, row.kpi].map((cell, index) => <td key={`${row.time}-${index}`} className={`px-3 py-4 ${index < 2 ? "font-black text-goodseed-950" : "font-semibold text-goodseed-700"}`}>{cell}</td>)}</tr>)}</tbody></table>
    </div>
  );
}

function TeamAssignmentView() {
  return <div className="grid gap-4 lg:grid-cols-2">{teamAssignments.map((item) => <article key={item.role} className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft"><div className="flex items-start justify-between gap-3"><div><Badge className={item.badge}>{item.role}</Badge><h3 className="mt-3 text-xl font-black text-goodseed-950">{item.people}</h3></div><Icon name="users" className="h-7 w-7 text-goodseed-700" /></div><p className="mt-4 text-sm font-semibold leading-7 text-goodseed-700">{item.access}</p><div className="mt-4 grid gap-2 sm:grid-cols-2"><span className="rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800">Scope: {item.scope}</span><span className="rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800">{item.status}</span></div></article>)}</div>;
}

function ProgressTrackingView() {
  return <div className="space-y-4">{progressItems.map((item) => <article key={item.task} className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft"><div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between"><div><h3 className="text-lg font-black text-goodseed-950">{item.task}</h3><div className="mt-2 flex flex-wrap gap-2"><StatusBadge status={item.status} /><Badge className={item.risk === "High" ? "bg-red-100 text-red-700 ring-red-200" : item.risk === "Medium" ? "bg-amber-100 text-amber-800 ring-amber-200" : "bg-goodseed-100 text-goodseed-800 ring-goodseed-200"}>Risk {item.risk}</Badge><Badge className="bg-white text-goodseed-700 ring-goodseed-100">{item.approval}</Badge></div></div><p className="rounded-lg bg-goodseed-50 px-4 py-3 text-sm font-black text-goodseed-800">{item.delay}</p></div><div className="mt-4 grid gap-4 lg:grid-cols-2"><div><div className="mb-2 flex justify-between text-xs font-black text-goodseed-700"><span>Planned %</span><span>{item.planned}%</span></div><MiniProgress value={item.planned} className="bg-slate-500" /></div><div><div className="mb-2 flex justify-between text-xs font-black text-goodseed-700"><span>Actual %</span><span>{item.actual}%</span></div><MiniProgress value={item.actual} /></div></div><div className="mt-4 grid gap-3 md:grid-cols-3">{item.evidence.map((evidence) => <div key={evidence} className="rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800"><Icon name="camera" className="mb-2 h-5 w-5" />{evidence}</div>)}</div></article>)}</div>;
}

function KpiDashboardView() {
  return (
    <div className="space-y-5">
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">{kpiCards.map((kpi) => <div key={kpi.category} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft"><p className="text-sm font-black text-goodseed-700">{kpi.category}</p><p className="mt-2 text-3xl font-black text-goodseed-950">{kpi.value} <span className="text-sm text-goodseed-600">{kpi.unit}</span></p><p className="mt-1 text-xs font-semibold leading-5 text-goodseed-700">{kpi.detail}</p><div className="mt-4"><MiniProgress value={kpi.progress} /></div></div>)}</div>
      <div className="grid gap-4 xl:grid-cols-[1fr_1fr_0.8fr]"><DashboardPanel title="Weekly / Monthly / Yearly Summary"><BarChart /><div className="mt-4 grid gap-2 sm:grid-cols-3">{["Weekly 89%", "Monthly 76%", "Yearly 58%"].map((item) => <span key={item} className="rounded-lg bg-goodseed-50 p-3 text-center text-sm font-black text-goodseed-800">{item}</span>)}</div></DashboardPanel><DashboardPanel title="Progress Circle"><DonutChart /></DashboardPanel><DashboardPanel title="Team Performance Ranking"><div className="space-y-3">{[["คุณหวาน", 94], ["พี่ไกร", 88], ["รุ่งนภา", 91], ["พี่สมชาย", 82], ["มนต์ชัย", 68]].sort((a, b) => b[1] - a[1]).map(([name, score], index) => <div key={name} className="rounded-lg bg-goodseed-50 p-3"><div className="flex justify-between text-sm font-black text-goodseed-900"><span>{index + 1}. {name}</span><span>{score}</span></div><div className="mt-2"><MiniProgress value={score} className={score < 75 ? "bg-red-500" : "bg-goodseed-600"} /></div></div>)}</div></DashboardPanel></div>
    </div>
  );
}

function FarmWorkPlanningPage({ viewMode, initialTab = "weekly" }) {
  const [activeTab, setActiveTab] = useState(initialTab);
  useEffect(() => setActiveTab(initialTab), [initialTab]);
  const active = workPlanTabs.find((tab) => tab.id === activeTab) || workPlanTabs[2];

  return (
    <section id="work-planning" className="print-area space-y-5">
      <div className="overflow-hidden rounded-lg border border-goodseed-100 bg-white shadow-soft">
        <div className="grid gap-5 bg-goodseed-900 p-5 text-white lg:grid-cols-[1fr_auto] lg:items-end"><div><Badge className="bg-white/15 text-white ring-white/20">Smart Farm Organization</Badge><h2 className="mt-3 text-2xl font-black leading-tight sm:text-3xl">Farm Work Planning & KPI Management</h2><p className="mt-2 max-w-4xl text-sm font-semibold leading-7 text-goodseed-50">วางแผนงานฟาร์มจากรายปีลงมาถึงรายชั่วโมง สั่งงานทีมภาคสนาม ติดตามหลักฐานจริง และประเมิน KPI จากข้อมูลเดียวกัน</p></div><div className="grid grid-cols-3 gap-2 text-center">{[["งานเดือนนี้", "145"], ["เสร็จตามแผน", "89%"], ["KPI เฉลี่ย", "86"]].map(([label, value]) => <div key={label} className="rounded-lg bg-white/10 p-3 ring-1 ring-white/15"><p className="text-xs font-bold text-goodseed-100">{label}</p><p className="text-2xl font-black">{value}</p></div>)}</div></div>
        <div className="space-y-3 p-4"><div className="thin-scrollbar flex gap-2 overflow-x-auto pb-1">{workPlanTabs.map((tab) => <button key={tab.id} onClick={() => setActiveTab(tab.id)} className={`min-w-fit rounded-lg px-4 py-3 text-left text-xs font-black transition ${activeTab === tab.id ? "bg-goodseed-700 text-white shadow-sm" : "bg-goodseed-50 text-goodseed-800 hover:bg-goodseed-100"}`}>{tab.label}<span className="block text-[11px] opacity-80">{tab.th}</span></button>)}</div><WorkPlanningFilterBar /><WorkPlanningActions /></div>
      </div>
      <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft"><div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between"><div><p className="text-xs font-black text-goodseed-600">Current View</p><h3 className="text-xl font-black text-goodseed-950">{active.label} / {active.th}</h3></div><Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{viewMode === "mobile" ? "Field Mobile Focus" : viewMode === "tablet" ? "Tablet Weekly/Daily Focus" : "Owner / Manager Full View"}</Badge></div>{activeTab === "yearly" && <YearlyPlanView setActiveTab={setActiveTab} />}{activeTab === "monthly" && <MonthlyPlanView setActiveTab={setActiveTab} />}{activeTab === "weekly" && <WeeklyPlanView setActiveTab={setActiveTab} />}{activeTab === "daily" && <DailyPlanView />}{activeTab === "hourly" && <HourlyTasksView />}{activeTab === "team" && <TeamAssignmentView />}{activeTab === "progress" && <ProgressTrackingView />}{activeTab === "kpi" && <KpiDashboardView />}</div>
    </section>
  );
}

const publicNavItems = [
  ["Home", "public-home"],
  ["About Us", "public-about"],
  ["Our Farm", "public-farm"],
  ["Products", "public-products"],
  ["Smart Farm & Technology", "public-technology"],
  ["Sustainability / ESG", "public-esg"],
  ["News & Activities", "public-news"],
  ["Gallery / Media", "public-gallery"],
  ["Company Profile", "public-company-profile"],
  ["Contact Us", "public-contact"],
];

const publicNavIconMap = {
  "public-home": "home",
  "public-about": "leaf",
  "public-farm": "tree",
  "public-products": "bag",
  "public-technology": "assets",
  "public-esg": "shield",
  "public-news": "news",
  "public-gallery": "book",
  "public-company-profile": "building",
  "public-contact": "phone",
};

const publicFarmStats = [
  { key: "farmArea", label: "พื้นที่พัฒนาฟาร์ม", value: "42 ไร่", detail: "ไม้ล้อมและเกษตรผสมผสาน" },
  { key: "currentTrees", label: "ต้นไม้ปัจจุบัน", value: "3,354 ต้น", detail: "รอบปลูก A-C" },
  { key: "expansionGoal", label: "เป้าหมายหลังขยาย", value: "6,942 ต้น", detail: "รอบปลูก A-F" },
  { key: "traceability", label: "ระบบตรวจสอบ", value: "QR + Real-time", detail: "Traceability ทุกแปลง" },
];

const publicHomeDefaults = {
  heroImage: homeHeroImage,
  eyebrow: "Company Profile Online",
  title: "GOODSEED FARM",
  subheading: "ฟาร์มไม้ล้อมและเกษตรผสมผสานสมัยใหม่ เพื่อการเติบโตอย่างยั่งยืน เชื่อมโยงการเกษตรคุณภาพ มาตรฐานการผลิต และอนาคตของตลาดส่งออก",
  visionLabel: "VISION",
  visionYear: "2030",
  stats: publicFarmStats.map((stat) => ({ ...stat })),
};

const goodSeedMapsLink = "https://maps.app.goo.gl/WyQgrVGJxEEFUzU49";

const publicDownloadCategories = [
  "Company Profile",
  "Farm Overview",
  "Product Information",
  "Export Information",
  "R&D Report",
  "Farm Standard / Certificate",
  "News & Update",
  "Media / Gallery",
  "Financial Summary แบบเผยแพร่ได้",
  "Other Documents",
];

const publicDownloadTypes = ["PDF", "Image", "Excel", "Word", "PowerPoint", "ZIP", "Other"];
const publicDownloadStatuses = ["แสดง", "ซ่อน", "เฉพาะหลังบ้าน"];

const publicDownloadTypeStyles = {
  PDF: { icon: "file", className: "bg-red-50 text-red-700 ring-red-100", extension: "pdf" },
  Image: { icon: "camera", className: "bg-emerald-50 text-emerald-700 ring-emerald-100", extension: "jpg" },
  Excel: { icon: "file", className: "bg-green-50 text-green-700 ring-green-100", extension: "xlsx" },
  Word: { icon: "file", className: "bg-blue-50 text-blue-700 ring-blue-100", extension: "docx" },
  PowerPoint: { icon: "file", className: "bg-orange-50 text-orange-700 ring-orange-100", extension: "pptx" },
  ZIP: { icon: "archive", className: "bg-purple-50 text-purple-700 ring-purple-100", extension: "zip" },
  Other: { icon: "box", className: "bg-slate-50 text-slate-700 ring-slate-100", extension: "txt" },
};

const initialPublicDownloadFiles = [
  {
    id: "public-file-profile",
    title: "GOODSEED Farm Company Profile",
    category: "Company Profile",
    description: "ภาพรวมตัวตนของฟาร์มไม้ล้อม ระบบจัดการฟาร์ม และทิศทางการพัฒนา GOODSEED Farm",
    uploadDate: "28 พ.ค. 2569",
    uploader: "Owner",
    responsible: "คุณสมชาย",
    type: "PDF",
    size: "8.4 MB",
    status: "แสดง",
    preview: "/public/company-profile/about-us-hero.jpg",
    note: "เอกสารเผยแพร่หลักของฟาร์ม",
    ownerDeleteAllowed: false,
  },
  {
    id: "public-file-farm-overview",
    title: "Farm Overview & Master Plan",
    category: "Farm Overview",
    description: "ผังรวมรอบปลูก A-C พื้นที่พัฒนา 42 ไร่ และแผนขยายรอบปลูก A-F",
    uploadDate: "27 พ.ค. 2569",
    uploader: "Admin Farm",
    responsible: "คุณหวาน",
    type: "Image",
    size: "4.8 MB",
    status: "แสดง",
    preview: "/public/farm-maps/farm-master-plan-new.jpg",
    note: "ใช้ประกอบการอธิบายภาพรวมฟาร์ม",
    ownerDeleteAllowed: true,
  },
  {
    id: "public-file-products",
    title: "Product Information Pack",
    category: "Product Information",
    description: "ข้อมูลไม้ล้อมและผลิตภัณฑ์เสริมจากฟาร์ม เช่น Biochar, Wood Vinegar และ Sustainable Farming Set",
    uploadDate: "26 พ.ค. 2569",
    uploader: "Manager",
    responsible: "Admin Farm",
    type: "PowerPoint",
    size: "12.2 MB",
    status: "แสดง",
    preview: "/public/coming-soon-products/product-showcase.jpg",
    note: "ชุดข้อมูลสำหรับเผยแพร่ภาพรวมสินค้า",
    ownerDeleteAllowed: true,
  },
  {
    id: "public-file-rd",
    title: "R&D Sweet Potato Weekly Record",
    category: "R&D Report",
    description: "ตัวอย่างแบบฟอร์มบันทึกผลการทดลองปลูกมันญี่ปุ่นรายสัปดาห์และข้อมูลการติดตามผล",
    uploadDate: "25 พ.ค. 2569",
    uploader: "R&D Team",
    responsible: "คุณหวาน",
    type: "PDF",
    size: "3.6 MB",
    status: "เฉพาะหลังบ้าน",
    preview: "/public/rd/sweet-potato-weekly-record.png",
    note: "เห็นเฉพาะทีมภายในที่ได้รับสิทธิ์",
    ownerDeleteAllowed: true,
  },
  {
    id: "public-file-certificate",
    title: "Farm Standard & Certificate",
    category: "Farm Standard / Certificate",
    description: "พื้นที่สำหรับจัดเก็บเอกสารมาตรฐานฟาร์ม ใบรับรอง และไฟล์ตรวจสอบที่เผยแพร่ได้",
    uploadDate: "24 พ.ค. 2569",
    uploader: "Admin Farm",
    responsible: "Owner",
    type: "Word",
    size: "1.9 MB",
    status: "ซ่อน",
    preview: "",
    note: "รอตรวจสอบก่อนเปิดแสดง",
    ownerDeleteAllowed: false,
  },
  {
    id: "public-file-media",
    title: "Media Gallery ZIP",
    category: "Media / Gallery",
    description: "ชุดรูปภาพมุมสูง ภาพแปลง และภาพกิจกรรมสำหรับงานประชาสัมพันธ์ของฟาร์ม",
    uploadDate: "23 พ.ค. 2569",
    uploader: "Media Admin",
    responsible: "Admin Farm",
    type: "ZIP",
    size: "38.5 MB",
    status: "แสดง",
    preview: "/public/gallery-media/goodseed-vision-2030.jpg",
    note: "รวมไฟล์ภาพเผยแพร่คุณภาพสูง",
    ownerDeleteAllowed: true,
  },
];

const emptyPublicDownloadForm = {
  title: "",
  category: publicDownloadCategories[0],
  description: "",
  fileName: "",
  preview: "",
  previewFileName: "",
  type: "PDF",
  status: "แสดง",
  uploadDate: "28 พ.ค. 2569",
  responsible: "",
  note: "",
};

function canManagePublicDownload(role) {
  return isOwnerRole(role) || ["admin", "manager", "developer"].includes(role);
}

function canDeletePublicDownload(role, file) {
  if (isOwnerRole(role) || role === "developer") return true;
  return ["admin", "manager"].includes(role) && file.ownerDeleteAllowed;
}

function canViewPublicDownload(role, file) {
  if (isOwnerRole(role) || ["admin", "manager", "developer"].includes(role)) return true;
  if (file.status === "เฉพาะหลังบ้าน") return role === "staff";
  return file.status === "แสดง";
}

function PublicDownloadTypeBadge({ type }) {
  const style = publicDownloadTypeStyles[type] || publicDownloadTypeStyles.Other;
  return (
    <span className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-black ring-1 ${style.className}`}>
      <Icon name={style.icon} className="h-3.5 w-3.5" />
      {type}
    </span>
  );
}

function PublicDownloadCenter({ role }) {
  const [files, setFiles] = useState(initialPublicDownloadFiles);
  const [query, setQuery] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("ทั้งหมด");
  const [typeFilter, setTypeFilter] = useState("ทั้งหมด");
  const [statusFilter, setStatusFilter] = useState("ทั้งหมด");
  const [sortOrder, setSortOrder] = useState("ล่าสุด");
  const [formOpen, setFormOpen] = useState(false);
  const [editingFile, setEditingFile] = useState(null);
  const [form, setForm] = useState(emptyPublicDownloadForm);
  const [previewFile, setPreviewFile] = useState(null);
  const [confirm, setConfirm] = useState(null);
  const [toast, setToast] = useState("");
  const canManage = canManagePublicDownload(role);

  const visibleFiles = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    return files
      .filter((file) => canViewPublicDownload(role, file))
      .filter((file) => categoryFilter === "ทั้งหมด" || file.category === categoryFilter)
      .filter((file) => typeFilter === "ทั้งหมด" || file.type === typeFilter)
      .filter((file) => statusFilter === "ทั้งหมด" || file.status === statusFilter)
      .filter((file) => !normalized || `${file.title} ${file.category} ${file.description} ${file.responsible}`.toLowerCase().includes(normalized))
      .sort((a, b) => sortOrder === "ล่าสุด" ? b.id.localeCompare(a.id) : a.id.localeCompare(b.id));
  }, [files, query, categoryFilter, typeFilter, statusFilter, sortOrder, role]);

  const openCreateForm = () => {
    setEditingFile(null);
    setForm(emptyPublicDownloadForm);
    setFormOpen(true);
  };

  const openEditForm = (file) => {
    setEditingFile(file);
    setForm({
      title: file.title,
      category: file.category,
      description: file.description,
      fileName: file.fileName || file.title,
      preview: file.preview || "",
      previewFileName: "",
      type: file.type,
      status: file.status,
      uploadDate: file.uploadDate,
      responsible: file.responsible || file.uploader,
      note: file.note || "",
    });
    setFormOpen(true);
  };

  const saveFile = (event) => {
    event.preventDefault();
    const payload = {
      ...form,
      title: form.title || "เอกสารใหม่ GOODSEED Farm",
      description: form.description || "เอกสารและข้อมูลเผยแพร่ของฟาร์ม",
      uploader: roleInfo(role).label,
      responsible: form.responsible || roleInfo(role).label,
      size: editingFile?.size || (form.fileName ? "ไฟล์ใหม่" : "Mock file"),
      ownerDeleteAllowed: editingFile?.ownerDeleteAllowed ?? true,
    };
    if (editingFile) {
      setFiles((current) => current.map((file) => file.id === editingFile.id ? { ...file, ...payload } : file));
      setToast("แก้ไขข้อมูลเอกสารสำเร็จ");
    } else {
      setFiles((current) => [{ id: `public-file-${Date.now()}`, ...payload }, ...current]);
      setToast("เพิ่มเอกสารใหม่สำเร็จ");
    }
    setFormOpen(false);
  };

  const deleteFile = (file) => {
    setConfirm({
      message: `ต้องการลบ "${file.title}" ออกจาก Download Center หรือไม่`,
      onConfirm: () => {
        setFiles((current) => current.filter((item) => item.id !== file.id));
        setConfirm(null);
        setToast("ลบเอกสารสำเร็จ");
      },
    });
  };

  const downloadPublicFile = (file) => {
    const extension = (publicDownloadTypeStyles[file.type] || publicDownloadTypeStyles.Other).extension;
    const content = [
      "GOODSEED Farm Download Center",
      `Document: ${file.title}`,
      `Category: ${file.category}`,
      `Description: ${file.description}`,
      `Uploaded: ${file.uploadDate}`,
      `Responsible: ${file.responsible || file.uploader}`,
      `Status: ${file.status}`,
      `Note: ${file.note || "-"}`,
    ].join("\n");
    downloadFile(`${file.title.replace(/\s+/g, "-").toLowerCase()}.${extension}`, content, "text/plain;charset=utf-8");
    setToast(`ดาวน์โหลด "${file.title}" แล้ว`);
  };

  return (
    <div className="mx-auto max-w-7xl px-4 lg:px-6">
      <PublicSectionTitle dark eyebrow="Company Profile" title="Download Center" subtitle="ศูนย์รวมเอกสาร รูปภาพ รายงาน และข้อมูลสำคัญของ GOODSEED Farm สำหรับการรับรู้ข้อมูลข่าวสารของฟาร์ม" />

      <div className="rounded-[28px] border border-white/10 bg-white/[0.08] p-4 shadow-2xl backdrop-blur md:p-6">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div className="max-w-3xl">
            <Badge className="bg-white/15 text-white ring-white/20">เอกสารและข้อมูลเผยแพร่ของฟาร์ม</Badge>
            <p className="mt-4 text-sm font-semibold leading-7 text-goodseed-50">
              พื้นที่นี้ใช้สำหรับจัดเก็บและเผยแพร่ข้อมูลสำคัญของ GOODSEED Farm โดยผู้ดูแลระบบสามารถเพิ่ม แก้ไข ลบ หรือซ่อนไฟล์ได้ตามความเหมาะสม เพื่อให้ข้อมูลของฟาร์มเป็นปัจจุบันอยู่เสมอ
            </p>
          </div>
          {canManage && (
            <button type="button" onClick={openCreateForm} className="inline-flex min-h-12 items-center justify-center gap-2 rounded-2xl bg-white px-5 py-3 text-sm font-black text-goodseed-900 shadow-sm transition hover:bg-goodseed-50">
              <Icon name="plus" className="h-4 w-4" />+ เพิ่มเอกสารใหม่
            </button>
          )}
        </div>

        <div className="mt-6 grid gap-3 rounded-[24px] border border-white/10 bg-goodseed-900/70 p-4 lg:grid-cols-[1.4fr_1fr_1fr_1fr_0.8fr]">
          <label className="relative">
            <Icon name="file" className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-goodseed-200" />
            <input
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              className="h-12 w-full rounded-xl border border-white/10 bg-white/10 pl-10 pr-3 text-sm font-bold text-white outline-none placeholder:text-goodseed-100 focus:border-goodseed-200"
              placeholder="ค้นหาชื่อเอกสาร หมวดหมู่ หรือผู้รับผิดชอบ"
            />
          </label>
          <select value={categoryFilter} onChange={(event) => setCategoryFilter(event.target.value)} className="h-12 rounded-xl border border-white/10 bg-white/10 px-3 text-sm font-bold text-white outline-none focus:border-goodseed-200">
            {["ทั้งหมด", ...publicDownloadCategories].map((item) => <option key={item} className="text-goodseed-950">{item}</option>)}
          </select>
          <select value={typeFilter} onChange={(event) => setTypeFilter(event.target.value)} className="h-12 rounded-xl border border-white/10 bg-white/10 px-3 text-sm font-bold text-white outline-none focus:border-goodseed-200">
            {["ทั้งหมด", ...publicDownloadTypes].map((item) => <option key={item} className="text-goodseed-950">{item}</option>)}
          </select>
          <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value)} className="h-12 rounded-xl border border-white/10 bg-white/10 px-3 text-sm font-bold text-white outline-none focus:border-goodseed-200">
            {["ทั้งหมด", ...publicDownloadStatuses].map((item) => <option key={item} className="text-goodseed-950">{item}</option>)}
          </select>
          <select value={sortOrder} onChange={(event) => setSortOrder(event.target.value)} className="h-12 rounded-xl border border-white/10 bg-white/10 px-3 text-sm font-bold text-white outline-none focus:border-goodseed-200">
            {["ล่าสุด", "เก่าสุด"].map((item) => <option key={item} className="text-goodseed-950">{item}</option>)}
          </select>
        </div>

        <div className="mt-6 grid gap-5 md:grid-cols-2 xl:grid-cols-3">
          {visibleFiles.map((file) => {
            const typeStyle = publicDownloadTypeStyles[file.type] || publicDownloadTypeStyles.Other;
            const statusTone = file.status === "แสดง" ? "bg-emerald-100 text-emerald-800 ring-emerald-200" : file.status === "ซ่อน" ? "bg-slate-100 text-slate-700 ring-slate-200" : "bg-amber-100 text-amber-800 ring-amber-200";
            return (
              <article key={file.id} className="flex min-h-[430px] flex-col overflow-hidden rounded-[26px] border border-white/10 bg-white text-goodseed-950 shadow-soft">
                <div className="h-44 bg-goodseed-50 p-3">
                  {file.preview ? (
                    <img src={file.preview} alt={file.title} className="h-full w-full rounded-[18px] object-cover" />
                  ) : (
                    <div className="grid h-full place-items-center rounded-[18px] bg-goodseed-100 text-goodseed-700">
                      <Icon name={typeStyle.icon} className="h-12 w-12" />
                    </div>
                  )}
                </div>
                <div className="flex flex-1 flex-col p-5">
                  <div className="flex flex-wrap items-center gap-2">
                    <PublicDownloadTypeBadge type={file.type} />
                    <Badge className={statusTone}>{file.status}</Badge>
                  </div>
                  <h3 className="mt-4 text-xl font-black leading-snug text-goodseed-950">{file.title}</h3>
                  <p className="mt-2 text-xs font-black uppercase tracking-[0.14em] text-goodseed-500">{file.category}</p>
                  <p className="mt-3 flex-1 text-sm font-semibold leading-7 text-goodseed-700">{file.description}</p>
                  <dl className="mt-4 grid gap-2 rounded-2xl bg-goodseed-50 p-4 text-xs font-bold text-goodseed-700">
                    <div className="flex justify-between gap-3"><dt>วันที่อัปโหลด</dt><dd className="text-right text-goodseed-950">{file.uploadDate}</dd></div>
                    <div className="flex justify-between gap-3"><dt>ผู้เพิ่มข้อมูล</dt><dd className="text-right text-goodseed-950">{file.uploader}</dd></div>
                    <div className="flex justify-between gap-3"><dt>ขนาดไฟล์</dt><dd className="text-right text-goodseed-950">{file.size}</dd></div>
                  </dl>
                  <div className="mt-4 grid gap-2 sm:grid-cols-2">
                    <button type="button" onClick={() => setPreviewFile(file)} className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-4 py-2 text-sm font-black text-white transition hover:bg-goodseed-800">
                      <Icon name="file" className="h-4 w-4" />ดูไฟล์
                    </button>
                    <button type="button" onClick={() => downloadPublicFile(file)} className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl border border-goodseed-200 bg-white px-4 py-2 text-sm font-black text-goodseed-800 transition hover:bg-goodseed-50">
                      <Icon name="download" className="h-4 w-4" />ดาวน์โหลด
                    </button>
                    {canManage && (
                      <button type="button" onClick={() => openEditForm(file)} className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl bg-goodseed-50 px-4 py-2 text-sm font-black text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-100">
                        <Icon name="edit" className="h-4 w-4" />แก้ไข
                      </button>
                    )}
                    {canDeletePublicDownload(role, file) && (
                      <button type="button" onClick={() => deleteFile(file)} className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl bg-red-50 px-4 py-2 text-sm font-black text-red-700 ring-1 ring-red-100 transition hover:bg-red-100">
                        <Icon name="trash" className="h-4 w-4" />ลบ
                      </button>
                    )}
                  </div>
                </div>
              </article>
            );
          })}
        </div>

        {!visibleFiles.length && (
          <div className="mt-6 rounded-[24px] border border-white/10 bg-white/10 p-8 text-center text-sm font-bold text-goodseed-50">
            ไม่พบเอกสารตามเงื่อนไขที่เลือก
          </div>
        )}
      </div>

      {formOpen && (
        <div className="fixed inset-0 z-[100] grid place-items-center bg-goodseed-950/65 p-4 backdrop-blur-sm">
          <form onSubmit={saveFile} className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-[28px] border border-goodseed-100 bg-white p-6 text-goodseed-950 shadow-2xl">
            <div className="flex items-start justify-between gap-4">
              <div>
                <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{editingFile ? "แก้ไขข้อมูลเอกสาร" : "เพิ่มเอกสารใหม่"}</Badge>
                <h3 className="mt-3 text-2xl font-black text-goodseed-950">{editingFile ? editingFile.title : "Upload Document"}</h3>
                <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">รองรับ PDF, รูปภาพ, Excel, Word, PowerPoint, ZIP และไฟล์อื่น ๆ ที่จำเป็นในอนาคต</p>
              </div>
              <button type="button" onClick={() => setFormOpen(false)} className="grid h-10 w-10 place-items-center rounded-full bg-goodseed-50 text-goodseed-700 hover:bg-goodseed-100">
                <Icon name="x" className="h-5 w-5" />
              </button>
            </div>
            <div className="mt-6 grid gap-4 md:grid-cols-2">
              <Input label="ชื่อเอกสาร" value={form.title} onChange={(value) => setForm((current) => ({ ...current, title: value }))} />
              <Select label="หมวดหมู่เอกสาร" value={form.category} onChange={(value) => setForm((current) => ({ ...current, category: value }))} options={publicDownloadCategories} />
              <Textarea label="คำอธิบายสั้น" value={form.description} onChange={(value) => setForm((current) => ({ ...current, description: value }))} wide />
              <label>
                <span className="text-sm font-bold text-goodseed-800">อัปโหลดไฟล์</span>
                <input type="file" onChange={(event) => setForm((current) => ({ ...current, fileName: event.target.files?.[0]?.name || current.fileName }))} className="mt-2 w-full rounded-lg border border-goodseed-200 bg-white px-3 py-2.5 text-sm text-goodseed-900 outline-none focus:ring-2 focus:ring-goodseed-300" />
              </label>
              <label>
                <span className="text-sm font-bold text-goodseed-800">อัปโหลดรูป Preview</span>
                <input type="file" accept="image/*" onChange={(event) => setForm((current) => ({ ...current, previewFileName: event.target.files?.[0]?.name || current.previewFileName }))} className="mt-2 w-full rounded-lg border border-goodseed-200 bg-white px-3 py-2.5 text-sm text-goodseed-900 outline-none focus:ring-2 focus:ring-goodseed-300" />
                {form.previewFileName && <span className="mt-1 block text-xs font-semibold text-goodseed-600">ไฟล์ Preview: {form.previewFileName}</span>}
              </label>
              <Input label="Preview URL / Path" value={form.preview} onChange={(value) => setForm((current) => ({ ...current, preview: value }))} />
              <Select label="ประเภทไฟล์" value={form.type} onChange={(value) => setForm((current) => ({ ...current, type: value }))} options={publicDownloadTypes} />
              <Select label="สถานะการแสดงผล" value={form.status} onChange={(value) => setForm((current) => ({ ...current, status: value }))} options={publicDownloadStatuses} />
              <Input label="วันที่อัปโหลด" value={form.uploadDate} onChange={(value) => setForm((current) => ({ ...current, uploadDate: value }))} />
              <Input label="ผู้รับผิดชอบ" value={form.responsible} onChange={(value) => setForm((current) => ({ ...current, responsible: value }))} />
              <Textarea label="หมายเหตุ" value={form.note} onChange={(value) => setForm((current) => ({ ...current, note: value }))} wide />
            </div>
            <div className="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-end">
              <button type="button" onClick={() => setFormOpen(false)} className="min-h-11 rounded-xl border border-goodseed-200 px-5 py-2 text-sm font-black text-goodseed-800">ยกเลิก</button>
              <button type="submit" className="min-h-11 rounded-xl bg-goodseed-700 px-5 py-2 text-sm font-black text-white shadow-sm hover:bg-goodseed-800">บันทึกเอกสาร</button>
            </div>
          </form>
        </div>
      )}

      {previewFile && (
        <div className="fixed inset-0 z-[100] grid place-items-center bg-goodseed-950/65 p-4 backdrop-blur-sm">
          <div className="max-h-[90vh] w-full max-w-4xl overflow-y-auto rounded-[28px] border border-goodseed-100 bg-white p-6 text-goodseed-950 shadow-2xl">
            <div className="flex items-start justify-between gap-4">
              <div>
                <PublicDownloadTypeBadge type={previewFile.type} />
                <h3 className="mt-3 text-2xl font-black text-goodseed-950">{previewFile.title}</h3>
                <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{previewFile.description}</p>
              </div>
              <button type="button" onClick={() => setPreviewFile(null)} className="grid h-10 w-10 place-items-center rounded-full bg-goodseed-50 text-goodseed-700 hover:bg-goodseed-100">
                <Icon name="x" className="h-5 w-5" />
              </button>
            </div>
            <div className="mt-6 overflow-hidden rounded-[24px] border border-goodseed-100 bg-goodseed-50 p-4">
              {previewFile.preview ? (
                <img src={previewFile.preview} alt={previewFile.title} className="max-h-[520px] w-full rounded-[18px] object-contain" />
              ) : (
                <div className="grid min-h-[260px] place-items-center rounded-[18px] bg-white text-center text-goodseed-800">
                  <div>
                    <Icon name={(publicDownloadTypeStyles[previewFile.type] || publicDownloadTypeStyles.Other).icon} className="mx-auto h-16 w-16" />
                    <p className="mt-4 text-lg font-black">Preview สำหรับไฟล์ประเภท {previewFile.type}</p>
                  </div>
                </div>
              )}
            </div>
            <div className="mt-5 grid gap-3 rounded-2xl bg-goodseed-50 p-4 text-sm font-bold text-goodseed-800 sm:grid-cols-2">
              <p>หมวดหมู่: <span className="text-goodseed-950">{previewFile.category}</span></p>
              <p>สถานะ: <span className="text-goodseed-950">{previewFile.status}</span></p>
              <p>วันที่อัปโหลด: <span className="text-goodseed-950">{previewFile.uploadDate}</span></p>
              <p>ผู้รับผิดชอบ: <span className="text-goodseed-950">{previewFile.responsible || previewFile.uploader}</span></p>
            </div>
            <div className="mt-6 flex justify-end">
              <button type="button" onClick={() => downloadPublicFile(previewFile)} className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-2 text-sm font-black text-white hover:bg-goodseed-800">
                <Icon name="download" className="h-4 w-4" />ดาวน์โหลด
              </button>
            </div>
          </div>
        </div>
      )}

      <CrudConfirmDialog confirm={confirm} onCancel={() => setConfirm(null)} onConfirm={() => confirm?.onConfirm?.()} />
      <CrudToast message={toast} onClose={() => setToast("")} />
    </div>
  );
}

function PublicSectionTitle({ eyebrow, title, subtitle, dark = false }) {
  return (
    <div className="mx-auto mb-8 max-w-3xl text-center">
      {eyebrow && <p className={`text-xs font-extrabold uppercase tracking-[0.28em] ${dark ? "text-goodseed-200" : "text-goodseed-600"}`}>{eyebrow}</p>}
      <h2 className={`mt-2 text-3xl font-extrabold leading-tight md:text-4xl ${dark ? "text-white" : "text-goodseed-950"}`}>{title}</h2>
      {subtitle && <p className={`mt-4 text-base font-semibold leading-8 ${dark ? "text-goodseed-100" : "text-goodseed-700"}`}>{subtitle}</p>}
    </div>
  );
}

function PublicWebsite({ onLogin, language, setLanguage, t, role }) {
  const [waitlistProduct, setWaitlistProduct] = useState(null);
  const [publicHome, setPublicHome] = useState(publicHomeDefaults);
  const [publicHomeDraft, setPublicHomeDraft] = useState(publicHomeDefaults);
  const [galleryItems, setGalleryItems] = useState(initialPublicGalleryItems);
  const [galleryDraft, setGalleryDraft] = useState({ title: "", category: "", src: "" });
  const [comingSoonItems, setComingSoonItems] = useState(publicComingSoonProducts.map((item, index) => ({ ...item, id: `coming-soon-${index}` })));
  const [comingSoonDraft, setComingSoonDraft] = useState({ name: "", category: "", image: "", description: "", features: "" });
  const [newsItems, setNewsItems] = useState(newsPromotionItems.map((item, index) => ({ ...item, id: `public-news-${index}` })));
  const [newsDraft, setNewsDraft] = useState({ type: "", title: "", date: "", image: "", summary: "" });
  const [farmPlanItems, setFarmPlanItems] = useState(farmMapImages.map((item, index) => ({ ...item, id: `farm-plan-${index}` })));
  const [farmPlanDraft, setFarmPlanDraft] = useState({ title: "", detail: "", src: "" });
  const [editingFarmPlanId, setEditingFarmPlanId] = useState(null);
  const [detailItem, setDetailItem] = useState(null);
  const [zoomImage, setZoomImage] = useState(null);
  const canManageFarmPlan = isOwnerRole(role);
  const canManagePublicMedia = isOwnerRole(role) || ["admin", "developer"].includes(role);
  const updatePublicHomeDraft = (field, value) => setPublicHomeDraft((current) => ({ ...current, [field]: value }));
  const updatePublicHomeStat = (index, field, value) => {
    setPublicHomeDraft((current) => ({
      ...current,
      stats: current.stats.map((stat, statIndex) => statIndex === index ? { ...stat, [field]: value } : stat),
    }));
  };
  const savePublicHome = (event) => {
    event.preventDefault();
    setPublicHome({
      ...publicHomeDraft,
      stats: publicHomeDraft.stats.map((stat) => ({
        ...stat,
        label: stat.label.trim(),
        value: stat.value.trim(),
        detail: stat.detail.trim(),
      })),
    });
  };
  const resetPublicHome = () => {
    setPublicHome(publicHomeDefaults);
    setPublicHomeDraft(publicHomeDefaults);
  };
  const addGalleryItem = (event) => {
    event.preventDefault();
    if (!galleryDraft.title.trim() || !galleryDraft.src.trim()) return;
    setGalleryItems((current) => [
      { id: `gallery-${Date.now()}`, title: galleryDraft.title.trim(), category: galleryDraft.category.trim() || "Gallery", src: galleryDraft.src.trim() },
      ...current,
    ]);
    setGalleryDraft({ title: "", category: "", src: "" });
  };
  const removeGalleryItem = (id) => setGalleryItems((current) => current.filter((item) => item.id !== id));
  const addComingSoonItem = (event) => {
    event.preventDefault();
    if (!comingSoonDraft.name.trim() || !comingSoonDraft.image.trim()) return;
    setComingSoonItems((current) => [
      {
        id: `coming-soon-${Date.now()}`,
        name: comingSoonDraft.name.trim(),
        category: comingSoonDraft.category.trim() || "Coming Soon",
        image: comingSoonDraft.image.trim(),
        description: comingSoonDraft.description.trim(),
        features: comingSoonDraft.features.split(",").map((item) => item.trim()).filter(Boolean),
      },
      ...current,
    ]);
    setComingSoonDraft({ name: "", category: "", image: "", description: "", features: "" });
  };
  const removeComingSoonItem = (id) => setComingSoonItems((current) => current.filter((item) => item.id !== id));
  const addNewsItem = (event) => {
    event.preventDefault();
    if (!newsDraft.title.trim() || !newsDraft.image.trim()) return;
    setNewsItems((current) => [
      {
        id: `public-news-${Date.now()}`,
        type: newsDraft.type.trim() || "ประกาศฟาร์ม",
        title: newsDraft.title.trim(),
        date: newsDraft.date.trim() || "อัปเดตล่าสุด",
        status: "เผยแพร่",
        image: newsDraft.image.trim(),
        summary: newsDraft.summary.trim(),
        link: "#public-news",
      },
      ...current,
    ]);
    setNewsDraft({ type: "", title: "", date: "", image: "", summary: "" });
  };
  const removeNewsItem = (id) => setNewsItems((current) => current.filter((item) => item.id !== id));
  const resetFarmPlanForm = () => {
    setFarmPlanDraft({ title: "", detail: "", src: "" });
    setEditingFarmPlanId(null);
  };
  const saveFarmPlanItem = (event) => {
    event.preventDefault();
    if (!farmPlanDraft.title.trim() || !farmPlanDraft.src.trim()) return;
    const payload = {
      title: farmPlanDraft.title.trim(),
      detail: farmPlanDraft.detail.trim(),
      src: farmPlanDraft.src.trim(),
    };
    if (editingFarmPlanId) {
      setFarmPlanItems((current) => current.map((item) => item.id === editingFarmPlanId ? { ...item, ...payload } : item));
    } else {
      setFarmPlanItems((current) => [{ id: `farm-plan-${Date.now()}`, ...payload }, ...current]);
    }
    resetFarmPlanForm();
  };
  const editFarmPlanItem = (item) => {
    setEditingFarmPlanId(item.id);
    setFarmPlanDraft({ title: item.title, detail: item.detail, src: item.src });
    document.querySelector("#public-farm-admin")?.scrollIntoView({ behavior: "smooth", block: "center" });
  };
  const removeFarmPlanItem = (id) => setFarmPlanItems((current) => current.filter((item) => item.id !== id));
  const primaryProducts = [
    { name: "ไม้ล้อม", category: "Main Product", image: aboutImages.treesLandscape, detail: "ไม้ล้อมคุณภาพสำหรับโครงการภูมิทัศน์ จัดสวน และตลาดส่งออก", status: "สินค้าหลัก" },
    { name: "ไม้ประดับ", category: "Ornamental Trees", image: aboutImages.forestTrees, detail: "ไม้ประดับและไม้เศรษฐกิจที่คัดเลือกสายพันธุ์และดูแลระบบราก", status: "พร้อมพัฒนา" },
    { name: "ไบโอชาร์", category: "Biochar", image: "/public/farm-assets/product-biochar-packages.png", detail: "ผลิตภัณฑ์เสริมจากทรัพยากรในฟาร์มเพื่อสนับสนุนเกษตรยั่งยืน", status: "ผลิตภัณฑ์เสริม" },
    { name: "พืชทดลอง", category: "R&D Crops", image: aboutImages.supportingProducts, detail: "แหนแดง ถั่วบราซิล มันญี่ปุ่น และพืชหมุนเวียนเพื่อเรียนรู้ระบบผลิต", status: "R&D" },
  ];
  const orderChannels = ["LINE Official", "Facebook", "Website", "Shopee", "Lazada", "TikTok Shop"];
  const technologyItems = ["QR Tree Tracking", "Real-time Dashboard", "KPI Monitoring", "Smart Irrigation", "CCTV Monitoring", "Solar System", "Weather Station", "Google Form Reporting", "Data Analytics"];
  const esgTopics = [
    { title: "การฟื้นฟูดิน", detail: "ฟื้นฟูโครงสร้างดินด้วยอินทรียวัตถุ พืชคลุมดิน และข้อมูลจากแปลงจริง เพื่อลดการพึ่งพาสารเคมีระยะยาว" },
    { title: "Biochar", detail: "ใช้ไบโอชาร์จากทรัพยากรหมุนเวียนในฟาร์ม เพื่อเพิ่มการอุ้มน้ำ ธาตุอาหาร และลดของเสียจากระบบผลิต" },
    { title: "Water Management", detail: "บริหารน้ำผ่านระบบน้ำและโครงข่ายกระจายน้ำภายในฟาร์ม พร้อมติดตามสถานะเพื่อวางแผนรอบปลูก" },
    { title: "Vetiver System", detail: "ใช้แนวหญ้าแฝกช่วยลดการชะล้างหน้าดิน รักษาความชื้น และสร้างแนวป้องกันพื้นที่ปลูกอย่างเป็นระบบ" },
    { title: "Circular Agriculture", detail: "เปลี่ยนเศษวัสดุและผลพลอยได้ในฟาร์มให้กลับมาเป็นวัตถุดิบ สร้างคุณค่าใหม่ในระบบเกษตรหมุนเวียน" },
    { title: "Carbon Reduction", detail: "ลดการใช้สารเคมี เพิ่มวัสดุชีวภาพ และวางแผนพลังงานสะอาดเพื่อสนับสนุนเป้าหมายคาร์บอนต่ำ" },
    { title: "CSR Activities", detail: "พัฒนากิจกรรมความรู้ด้านเกษตรยั่งยืนร่วมกับทีมงาน ชุมชน และเครือข่ายเกษตรกรในพื้นที่" },
  ];
  return (
    <div className="min-h-screen bg-white text-goodseed-950">
      <header className="sticky top-0 z-40 bg-white/75 px-2 py-2 backdrop-blur-xl sm:px-4 sm:py-3">
        <div className="mx-auto flex max-w-[1500px] items-center gap-3 rounded-2xl border border-goodseed-100 bg-white/95 px-3 py-2 shadow-[0_18px_45px_rgba(23,52,25,0.10)] ring-1 ring-white/70">
          <a href="#public-home" className="hidden shrink-0 items-center gap-3 rounded-xl px-2 py-2 transition hover:bg-goodseed-50 lg:flex">
            <img src={farmLogo} alt="GOODSEED Farm" className="h-12 w-12 rounded-xl object-cover shadow-sm ring-1 ring-goodseed-100" />
            <div className="leading-tight">
              <p className="text-base font-extrabold text-goodseed-950">GOODSEED Farm</p>
              <p className="text-[11px] font-bold text-goodseed-600">Premium Smart Nursery</p>
            </div>
          </a>
          <nav className="thin-scrollbar flex min-w-0 flex-1 items-stretch gap-2 overflow-x-auto py-1">
            {publicNavItems.map(([label, id]) => (
              <a
                key={id}
                href={`#${id}`}
                className="group flex min-w-[82px] max-w-[118px] flex-col items-center justify-center gap-1.5 rounded-xl px-2 py-2.5 text-center text-goodseed-800 transition hover:-translate-y-0.5 hover:bg-goodseed-50 hover:shadow-sm focus:outline-none focus:ring-4 focus:ring-goodseed-100"
              >
                <Icon name={publicNavIconMap[id] || "leaf"} className="h-7 w-7 stroke-[2.2] text-goodseed-700 transition group-hover:text-goodseed-900" />
                <span className="max-w-full break-words text-[11px] font-extrabold leading-tight">{t(`publicNav.${id}`, label)}</span>
              </a>
            ))}
          </nav>
          <div className="flex shrink-0 items-center gap-2">
            <div className="hidden rounded-xl border border-goodseed-100 bg-white p-1 shadow-sm md:block">
              <LanguageToggle language={language} setLanguage={setLanguage} compact />
            </div>
            <a href="#public-contact" className="hidden min-h-[72px] min-w-[76px] flex-col items-center justify-center gap-1 rounded-xl border border-goodseed-100 bg-white px-3 py-2 text-center text-xs font-extrabold leading-tight text-goodseed-800 shadow-sm transition hover:bg-goodseed-50 lg:flex">
              <Icon name="headset" className="h-7 w-7 text-goodseed-700" />
              {t("actions.contact")}
            </a>
            <a href="#login" onClick={(event) => { event.preventDefault(); onLogin(); }} className="flex min-h-[72px] min-w-[78px] flex-col items-center justify-center gap-1 rounded-xl bg-goodseed-700 px-3 py-2 text-center text-xs font-extrabold leading-tight text-white shadow-lg shadow-goodseed-700/20 transition hover:-translate-y-0.5 hover:bg-goodseed-800">
              <Icon name="user" className="h-7 w-7" />
              {t("actions.login")}
            </a>
          </div>
        </div>
      </header>

      <main>
        <section
          id="public-home"
          className="relative isolate min-h-screen overflow-hidden bg-goodseed-950 bg-cover bg-center text-white"
          style={publicHome.heroImage ? { backgroundImage: `url(${publicHome.heroImage})` } : undefined}
        >
          <div
            className="absolute inset-0 -z-10"
            style={{
              background:
                "linear-gradient(116deg, rgba(2,22,10,0.88) 0%, rgba(8,48,22,0.74) 34%, rgba(11,42,18,0.30) 68%, rgba(0,0,0,0.08) 100%), linear-gradient(0deg, rgba(0,18,8,0.80) 0%, rgba(0,24,11,0.40) 36%, rgba(255,255,255,0.02) 78%)",
            }}
          />
          <div className="absolute left-0 top-0 -z-10 h-1/3 w-1/2 bg-gradient-to-br from-lime-300/22 via-goodseed-500/12 to-transparent" />

          <div className="mx-auto flex min-h-screen max-w-7xl flex-col px-4 py-6 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between gap-4">
              <a href="#public-home" className="inline-flex items-center gap-3 rounded-2xl border border-white/18 bg-goodseed-950/55 px-4 py-3 shadow-2xl backdrop-blur-md">
                <img src={farmLogo} alt="GoodSeed Farm logo" className="h-14 w-14 rounded-xl object-cover ring-1 ring-white/20" />
                <div>
                  <p className="text-base font-black leading-tight text-white">GoodSeed<br />Farm</p>
                  <p className="mt-1 text-[10px] font-extrabold uppercase tracking-[0.18em] text-lime-200">Smart Farm</p>
                </div>
              </a>
              <Badge className="hidden bg-goodseed-950/70 text-white shadow-lg ring-white/35 backdrop-blur-md sm:inline-flex">Company Profile Online</Badge>
            </div>

            <div className="flex flex-1 flex-col justify-end gap-8 pb-8 pt-16 lg:pb-10">
              <div className="max-w-4xl">
                <p
                  className="w-fit rounded-full border border-white/25 bg-goodseed-950/55 px-4 py-2 text-xs font-black uppercase tracking-[0.28em] text-white shadow-lg backdrop-blur-sm sm:text-sm"
                  style={{ backgroundColor: "rgba(5, 28, 13, 0.72)", textShadow: "0 2px 10px rgba(0,0,0,0.55)" }}
                >
                  {publicHome.eyebrow}
                </p>
                <h1
                  className="mt-4 text-5xl font-black uppercase leading-[0.9] tracking-[0.04em] text-white sm:text-6xl md:text-7xl lg:text-8xl"
                  style={{ textShadow: "0 8px 28px rgba(0,0,0,0.35)" }}
                >
                  {publicHome.title}
                </h1>
                <p className="mt-6 max-w-3xl text-lg font-bold leading-8 text-white sm:text-xl sm:leading-9 md:text-2xl">
                  {publicHome.subheading}
                </p>

                <div className="mt-8 max-w-3xl">
                  <div className="flex items-center gap-4">
                    <span className="h-px flex-1 bg-lime-400/70" />
                    <Icon name="leaf" className="h-6 w-6 text-lime-300" />
                    <span className="h-px flex-1 bg-lime-400/70" />
                  </div>
                  <div className="mt-5 flex flex-wrap items-baseline gap-x-5 gap-y-2">
                    <span className="text-4xl font-black uppercase tracking-[0.38em] text-white sm:text-5xl md:text-6xl">{publicHome.visionLabel}</span>
                    <span className="text-4xl font-black tracking-[0.22em] text-lime-400 sm:text-5xl md:text-6xl">{publicHome.visionYear}</span>
                  </div>
                </div>

                <div className="mt-9 grid gap-3 sm:flex sm:flex-wrap">
                  <a href="#public-products" className="inline-flex min-h-[52px] items-center justify-center rounded-full bg-goodseed-700 px-8 py-4 text-sm font-black text-white shadow-2xl transition duration-300 hover:-translate-y-0.5 hover:bg-goodseed-600">{t("actions.viewProducts")}</a>
                  <a href="#public-contact" className="inline-flex min-h-[52px] items-center justify-center rounded-full border border-white/55 bg-white/16 px-8 py-4 text-sm font-black text-white shadow-2xl backdrop-blur-md transition duration-300 hover:-translate-y-0.5 hover:bg-white/26">{t("actions.contact")}</a>
                  <a
                    href="#public-company-profile"
                    className="inline-flex min-h-[52px] items-center justify-center rounded-full border-2 border-white bg-white px-8 py-4 text-sm font-black text-goodseed-950 shadow-[0_16px_42px_rgba(0,0,0,0.36)] ring-2 ring-goodseed-950/20 transition duration-300 hover:-translate-y-0.5 hover:bg-lime-50"
                    style={{ backgroundColor: "#ffffff", color: "#173419", boxShadow: "0 16px 42px rgba(0,0,0,0.36)" }}
                  >
                    {t("actions.companyProfile")}
                  </a>
                </div>
              </div>

              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                {publicHome.stats.map((stat) => (
                  <div key={stat.label} className="rounded-2xl border border-white/25 bg-white/86 p-5 shadow-2xl backdrop-blur-md transition duration-300 hover:-translate-y-1 hover:bg-white/95">
                    <p className="text-sm font-black text-goodseed-800">{stat.label}</p>
                    <p className="mt-3 text-3xl font-black leading-tight text-goodseed-950">{stat.value}</p>
                    <p className="mt-2 text-sm font-bold leading-6 text-goodseed-700">{stat.detail}</p>
                  </div>
                ))}
              </div>

              <div className="grid gap-3 border-t border-white/14 pt-5 sm:grid-cols-2 lg:grid-cols-4">
                {[
                  ["Sustainable Future", "leaf"],
                  ["Innovative Growth", "tree"],
                  ["Community Together", "users"],
                  ["Better Planet For All", "map"],
                ].map(([label, icon]) => (
                  <div key={label} className="flex items-center gap-3 text-white/88">
                    <span className="grid h-12 w-12 shrink-0 place-items-center rounded-full border border-lime-300/45 bg-white/8 text-lime-200 backdrop-blur">
                      <Icon name={icon} className="h-6 w-6" />
                    </span>
                    <span className="text-sm font-black uppercase leading-5 tracking-[0.06em]">{label}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </section>

        {canManagePublicMedia && (
          <section id="public-home-admin" className="bg-goodseed-50 py-10">
            <div className="mx-auto max-w-7xl px-4 lg:px-6">
              <form onSubmit={savePublicHome} className="rounded-[24px] border border-goodseed-100 bg-white p-4 shadow-sm md:p-5">
                <div className="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.18em] text-goodseed-500">Web Admin</p>
                    <h3 className="mt-1 text-xl font-black text-goodseed-950">จัดการหน้าแรก Public Home</h3>
                    <p className="mt-1 text-sm font-bold text-goodseed-600">Owner / Admin สามารถเปลี่ยนรูป Hero หัวข้อ ข้อความ และตัวเลขสรุปหน้าแรกได้</p>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <button type="button" onClick={() => updatePublicHomeDraft("heroImage", "")} className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl bg-red-50 px-4 py-2 text-sm font-black text-red-700 ring-1 ring-red-100 hover:bg-red-100">
                      <Icon name="trash" className="h-4 w-4" />ลบรูป Hero
                    </button>
                    <button type="button" onClick={resetPublicHome} className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl bg-white px-4 py-2 text-sm font-black text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-50">
                      <Icon name="refresh" className="h-4 w-4" />คืนค่าเดิม
                    </button>
                    <button type="submit" className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-2 text-sm font-black text-white hover:bg-goodseed-800">
                      <Icon name="check" className="h-4 w-4" />บันทึกหน้าแรก
                    </button>
                  </div>
                </div>
                <div className="grid gap-3 lg:grid-cols-2">
                  <label className="block text-sm font-black text-goodseed-800">
                    รูปพื้นหลัง Hero
                    <input value={publicHomeDraft.heroImage} onChange={(event) => updatePublicHomeDraft("heroImage", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="/public/farm-assets/example.jpg หรือ https://..." />
                  </label>
                  <label className="block text-sm font-black text-goodseed-800">
                    ป้ายหัวข้อเล็ก
                    <input value={publicHomeDraft.eyebrow} onChange={(event) => updatePublicHomeDraft("eyebrow", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" />
                  </label>
                  <label className="block text-sm font-black text-goodseed-800">
                    หัวข้อหลัก
                    <input value={publicHomeDraft.title} onChange={(event) => updatePublicHomeDraft("title", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" />
                  </label>
                  <div className="grid gap-3 sm:grid-cols-2">
                    <label className="block text-sm font-black text-goodseed-800">
                      Vision Label
                      <input value={publicHomeDraft.visionLabel} onChange={(event) => updatePublicHomeDraft("visionLabel", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" />
                    </label>
                    <label className="block text-sm font-black text-goodseed-800">
                      Vision Year
                      <input value={publicHomeDraft.visionYear} onChange={(event) => updatePublicHomeDraft("visionYear", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" />
                    </label>
                  </div>
                  <label className="block text-sm font-black text-goodseed-800 lg:col-span-2">
                    ข้อความแนะนำหน้าแรก
                    <textarea value={publicHomeDraft.subheading} onChange={(event) => updatePublicHomeDraft("subheading", event.target.value)} rows="3" className="mt-2 w-full rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" />
                  </label>
                </div>
                <div className="mt-5 grid gap-3 lg:grid-cols-4">
                  {publicHomeDraft.stats.map((stat, index) => (
                    <div key={stat.key || index} className="rounded-2xl border border-goodseed-100 bg-goodseed-50 p-3">
                      <p className="mb-2 text-xs font-black uppercase tracking-[0.14em] text-goodseed-500">Stat {index + 1}</p>
                      <input value={stat.label} onChange={(event) => updatePublicHomeStat(index, "label", event.target.value)} className="mb-2 w-full rounded-xl border border-goodseed-100 bg-white px-3 py-2 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="ชื่อสถิติ" />
                      <input value={stat.value} onChange={(event) => updatePublicHomeStat(index, "value", event.target.value)} className="mb-2 w-full rounded-xl border border-goodseed-100 bg-white px-3 py-2 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="ตัวเลข / ค่า" />
                      <input value={stat.detail} onChange={(event) => updatePublicHomeStat(index, "detail", event.target.value)} className="w-full rounded-xl border border-goodseed-100 bg-white px-3 py-2 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="รายละเอียด" />
                    </div>
                  ))}
                </div>
              </form>
            </div>
          </section>
        )}

        <section id="public-coming-soon" className="bg-gradient-to-b from-goodseed-50 to-white py-16">
          <div className="mx-auto max-w-7xl px-4 lg:px-6">
            <PublicSectionTitle
              eyebrow="Coming Soon Products"
              title="สินค้าเตรียมเปิดจำหน่ายเร็ว ๆ นี้"
              subtitle="ผลิตภัณฑ์จาก GOODSEED Farm ที่พัฒนาจากแนวคิดเกษตรยั่งยืน ระบบฟาร์มสมัยใหม่ และการใช้ทรัพยากรอย่างคุ้มค่า"
            />
            {canManagePublicMedia && (
              <div className="mb-6 rounded-[24px] border border-goodseed-100 bg-white p-4 shadow-sm md:p-5">
                <div className="mb-4 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.18em] text-goodseed-500">Web Admin</p>
                    <h3 className="mt-1 text-xl font-black text-goodseed-950">จัดการรูปสินค้าเตรียมเปิดจำหน่าย</h3>
                    <p className="mt-1 text-sm font-bold text-goodseed-600">ผู้ดูแลเว็บสามารถเพิ่มหรือลบรูปสินค้าได้</p>
                  </div>
                  <Badge className="bg-goodseed-700 text-white ring-goodseed-700">{comingSoonItems.length} รายการ</Badge>
                </div>
                <form onSubmit={addComingSoonItem} className="grid gap-3 lg:grid-cols-[1fr_0.9fr_1.4fr_1.2fr_1fr_auto]">
                  <input value={comingSoonDraft.name} onChange={(event) => setComingSoonDraft((current) => ({ ...current, name: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="ชื่อสินค้า" aria-label="ชื่อสินค้าใหม่" />
                  <input value={comingSoonDraft.category} onChange={(event) => setComingSoonDraft((current) => ({ ...current, category: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="หมวดหมู่" aria-label="หมวดหมู่สินค้าใหม่" />
                  <input value={comingSoonDraft.image} onChange={(event) => setComingSoonDraft((current) => ({ ...current, image: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="/public/farm-assets/example.jpg" aria-label="URL หรือ public path รูปสินค้า" />
                  <input value={comingSoonDraft.description} onChange={(event) => setComingSoonDraft((current) => ({ ...current, description: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="รายละเอียดสินค้า" aria-label="รายละเอียดสินค้า" />
                  <input value={comingSoonDraft.features} onChange={(event) => setComingSoonDraft((current) => ({ ...current, features: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="จุดเด่น คั่นด้วย ," aria-label="จุดเด่นสินค้า" />
                  <button type="submit" className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-black text-white transition hover:bg-goodseed-800">
                    <Icon name="plus" className="h-4 w-4" />เพิ่มสินค้า
                  </button>
                </form>
              </div>
            )}
            <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-4">
              {comingSoonItems.map((product) => (
                <article key={product.id} className="group flex h-full flex-col overflow-hidden rounded-2xl border border-goodseed-100 bg-white shadow-soft transition hover:-translate-y-1 hover:shadow-lg">
                  <button
                    type="button"
                    onClick={() => setZoomImage({ title: product.name, detail: product.description, src: product.image })}
                    className="relative grid w-full shrink-0 place-items-center overflow-hidden border-b border-goodseed-100 bg-goodseed-50 p-3"
                    style={{ height: 260 }}
                  >
                    <img
                      src={product.image}
                      alt={product.name}
                      className="transition duration-500 group-hover:scale-105"
                      style={{ display: "block", maxHeight: "100%", maxWidth: "100%", objectFit: "contain" }}
                    />
                    <Badge className="absolute left-4 top-4 bg-amber-100 text-amber-800 ring-amber-200">Coming Soon</Badge>
                  </button>
                  <div className="relative z-10 flex flex-1 flex-col bg-white p-5">
                    <p className="text-xs font-extrabold uppercase tracking-[0.16em] text-goodseed-500">{product.category}</p>
                    <h3 className="mt-2 text-xl font-extrabold leading-tight text-goodseed-950">{product.name}</h3>
                    <p className="mt-3 flex-1 text-sm font-semibold leading-7 text-goodseed-700">{product.description}</p>
                    <div className="mt-4 flex flex-wrap gap-2">
                      {product.features.map((feature) => (
                        <span key={feature} className="rounded-full bg-goodseed-50 px-3 py-1 text-xs font-extrabold text-goodseed-700 ring-1 ring-goodseed-100">{feature}</span>
                      ))}
                    </div>
                    <div className="mt-5 grid gap-2 sm:grid-cols-2">
                      <button type="button" onClick={() => setDetailItem({ kind: "product", title: product.name, category: product.category, image: product.image, description: product.description, features: product.features })} className="inline-flex min-h-11 items-center justify-center rounded-xl border border-goodseed-200 px-4 py-2 text-sm font-extrabold text-goodseed-800 transition hover:bg-goodseed-50">ดูรายละเอียด</button>
                      <button type="button" onClick={() => setWaitlistProduct(product)} className="inline-flex min-h-11 items-center justify-center rounded-xl bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white transition hover:bg-goodseed-800">แจ้งเตือนเมื่อเปิดขาย</button>
                    </div>
                    <div className="mt-2 grid gap-2 sm:grid-cols-2">
                      <button type="button" onClick={() => setZoomImage({ title: product.name, detail: product.description, src: product.image })} className="inline-flex min-h-10 items-center justify-center rounded-xl bg-goodseed-50 px-4 py-2 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-100">ซูมรูป</button>
                      {canManagePublicMedia && (
                        <button type="button" onClick={() => removeComingSoonItem(product.id)} className="inline-flex min-h-10 items-center justify-center rounded-xl bg-red-50 px-4 py-2 text-xs font-black text-red-700 ring-1 ring-red-100 transition hover:bg-red-100">ลบรูป</button>
                      )}
                    </div>
                  </div>
                </article>
              ))}
            </div>
            <div className="mt-8 rounded-2xl border border-goodseed-100 bg-white p-5 shadow-soft lg:p-6">
              <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                <div>
                  <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-goodseed-500">Online Order System</p>
                  <h3 className="mt-2 text-2xl font-extrabold text-goodseed-950">ช่องทางการสั่งซื้อ</h3>
                  <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">เตรียมรองรับการขายออนไลน์ผ่านช่องทางหลักของ GOODSEED Farm พร้อมระบบแจ้งเตือนสินค้าเปิดขาย</p>
                </div>
                <div className="grid gap-2 sm:grid-cols-3 lg:min-w-[520px]">
                  {orderChannels.map((channel) => (
                    <button key={channel} type="button" className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-extrabold text-goodseed-800 transition hover:border-goodseed-300 hover:bg-goodseed-100">{channel}</button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </section>

        <section id="public-about" className="bg-white px-4 py-12 lg:px-6 lg:py-16">
          <div className="mx-auto max-w-7xl overflow-hidden rounded-2xl border border-goodseed-100 bg-white p-2 shadow-soft">
            <img
              src={aboutImages.whoWeAre}
              alt="About Us - Who We Are GoodSeed Farm"
              className="h-auto w-full object-contain"
            />
          </div>
        </section>

        <section id="public-farm" className="bg-goodseed-50 py-16">
          <div className="mx-auto max-w-7xl px-4 lg:px-6">
            <PublicSectionTitle eyebrow="Our Farm" title="Farm Master Plan" subtitle="ฟาร์มของเราวางผังการปลูกเป็นรอบและโซนอย่างชัดเจน เพื่อให้บริหารจัดการ ตรวจสอบ และขยายกำลังการผลิตได้อย่างเป็นระบบ" />
            {canManageFarmPlan && (
              <div id="public-farm-admin" className="mb-6 rounded-[24px] border border-goodseed-100 bg-white p-4 shadow-sm md:p-5">
                <div className="mb-4 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.18em] text-goodseed-500">Owner Only</p>
                    <h3 className="mt-1 text-xl font-black text-goodseed-950">จัดการรูปภาพผังฟาร์ม</h3>
                    <p className="mt-1 text-sm font-bold text-goodseed-600">สิทธิ์เพิ่ม แก้ไข และลบเป็นของเจ้าของฟาร์ม</p>
                  </div>
                  <Badge className="bg-goodseed-700 text-white ring-goodseed-700">{farmPlanItems.length} รูป</Badge>
                </div>
                <form onSubmit={saveFarmPlanItem} className="grid gap-3 lg:grid-cols-[1fr_1.4fr_1.4fr_auto_auto]">
                  <input
                    value={farmPlanDraft.title}
                    onChange={(event) => setFarmPlanDraft((current) => ({ ...current, title: event.target.value }))}
                    className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500"
                    placeholder="ชื่อผังฟาร์ม"
                    aria-label="ชื่อผังฟาร์ม"
                  />
                  <input
                    value={farmPlanDraft.detail}
                    onChange={(event) => setFarmPlanDraft((current) => ({ ...current, detail: event.target.value }))}
                    className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500"
                    placeholder="รายละเอียด"
                    aria-label="รายละเอียดผังฟาร์ม"
                  />
                  <input
                    value={farmPlanDraft.src}
                    onChange={(event) => setFarmPlanDraft((current) => ({ ...current, src: event.target.value }))}
                    className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500"
                    placeholder="/public/farm-assets/example.jpg หรือ https://..."
                    aria-label="URL หรือ public path ของรูปผังฟาร์ม"
                  />
                  <button type="submit" className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-black text-white transition hover:bg-goodseed-800">
                    <Icon name={editingFarmPlanId ? "edit" : "plus"} className="h-4 w-4" />{editingFarmPlanId ? "บันทึกแก้ไข" : "เพิ่มรูป"}
                  </button>
                  {editingFarmPlanId && (
                    <button type="button" onClick={resetFarmPlanForm} className="inline-flex min-h-12 items-center justify-center rounded-xl border border-goodseed-100 bg-white px-5 py-3 text-sm font-black text-goodseed-800 transition hover:bg-goodseed-50">
                      ยกเลิก
                    </button>
                  )}
                </form>
              </div>
            )}
            <div className="grid gap-5 lg:grid-cols-4">
              {farmPlanItems.map((item, index) => (
                <article key={item.id} className={`overflow-hidden rounded-2xl border border-goodseed-100 bg-white shadow-soft ${index === 0 ? "lg:col-span-4" : ""}`}>
                  <button
                    type="button"
                    onClick={() => setZoomImage(item)}
                    className={`${index === 0 ? "h-[420px] md:h-[560px]" : "h-80"} grid w-full place-items-center bg-goodseed-50 p-3 text-left transition hover:bg-goodseed-100`}
                    aria-label={`ซูมดู ${item.title}`}
                  >
                    <img src={item.src} alt={item.title} className="max-h-full max-w-full object-contain" />
                  </button>
                  <div className="p-5">
                    <p className="text-lg font-extrabold text-goodseed-950">{item.title}</p>
                    <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{item.detail}</p>
                    <div className="mt-4 flex flex-wrap gap-2">
                      <button type="button" onClick={() => setZoomImage(item)} className="inline-flex items-center gap-2 rounded-xl bg-goodseed-50 px-3 py-2 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-100">
                        <Icon name="layout" className="h-4 w-4" />ซูมดู
                      </button>
                      {canManageFarmPlan && (
                        <>
                          <button type="button" onClick={() => editFarmPlanItem(item)} className="inline-flex items-center gap-2 rounded-xl bg-white px-3 py-2 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-50">
                            <Icon name="edit" className="h-4 w-4" />แก้ไข
                          </button>
                          <button type="button" onClick={() => removeFarmPlanItem(item.id)} className="inline-flex items-center gap-2 rounded-xl bg-red-50 px-3 py-2 text-xs font-black text-red-700 ring-1 ring-red-100 transition hover:bg-red-100">
                            <Icon name="trash" className="h-4 w-4" />ลบ
                          </button>
                        </>
                      )}
                    </div>
                  </div>
                </article>
              ))}
            </div>
            <div className="mt-6 grid gap-4 md:grid-cols-3">
              {[
                {
                  title: "ระบบน้ำและโครงข่ายกระจายน้ำภายในฟาร์ม",
                  detail: "เชื่อมข้อมูล GPS Zone รูปภาพ และสถานะการพัฒนา เพื่อใช้วางแผนและบริหารการขยายรอบปลูก A–F อย่างเป็นระบบ",
                },
                {
                  title: "โรงเรือนและพื้นที่ทดลอง",
                  detail: "ติดตามสถานะพื้นที่ทดลอง โรงเรือน และโซนพัฒนา เพื่อเปรียบเทียบผลผลิตและวางแผนการขยายงาน",
                },
                {
                  title: "Before / After Development",
                  detail: "บันทึกภาพก่อนและหลังการพัฒนาพื้นที่ เพื่อสื่อสารความก้าวหน้ากับลูกค้า นักลงทุน และทีมงาน",
                },
              ].map((item) => (
                <div key={item.title} className="rounded-xl border border-goodseed-100 bg-white p-5 shadow-sm">
                  <Icon name="map" className="h-8 w-8 text-goodseed-700" />
                  <p className="mt-3 text-lg font-extrabold text-goodseed-900">{item.title}</p>
                  <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{item.detail}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        <section id="public-products" className="mx-auto max-w-7xl px-4 py-16 lg:px-6">
          <PublicSectionTitle eyebrow="Products" title="สินค้าและบริการจากฟาร์ม" subtitle="สินค้าหลักคือไม้ล้อม ส่วนผลิตภัณฑ์อื่นเป็นผลิตภัณฑ์เสริมจากฟาร์มเพื่อสนับสนุนระบบเกษตรยั่งยืน" />
          <article className="mb-6 overflow-hidden rounded-2xl border border-goodseed-100 bg-white shadow-soft">
            <div className="grid gap-0 lg:grid-cols-[1fr_1.1fr]">
              <img src={aboutImages.treesLandscape} alt="ไม้ล้อม GoodSeed Farm" className="h-full min-h-[360px] w-full object-cover object-center" />
              <div className="p-6 lg:p-10">
                <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Main Product</Badge>
                <h3 className="mt-4 text-3xl font-extrabold text-goodseed-950">ไม้ล้อมคุณภาพจาก GOODSEED Farm</h3>
                <p className="mt-4 text-base font-semibold leading-8 text-goodseed-700">เราคัดเลือกและดูแลไม้ล้อมตั้งแต่ระยะเริ่มต้น เพื่อให้ได้ต้นไม้ที่แข็งแรง ระบบรากดี ลำต้นสมบูรณ์ และพร้อมสำหรับงานภูมิทัศน์ โครงการจัดสวน และการพัฒนาสู่ตลาดส่งออกในอนาคต</p>
                <div className="mt-5 flex flex-wrap gap-2">
                  {landscapeTreeTypes.map((item) => <Badge key={item} className="bg-white text-goodseed-800 ring-goodseed-200">{item}</Badge>)}
                </div>
              </div>
            </div>
          </article>
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            {primaryProducts.map((product) => (
              <article key={product.name} className="rounded-xl border border-goodseed-100 bg-white p-4 shadow-sm">
                <img src={product.image} alt={product.name} className="h-36 w-full rounded-lg object-cover" />
                <p className="mt-4 text-xs font-extrabold uppercase text-goodseed-500">{product.category}</p>
                <h3 className="mt-1 text-xl font-extrabold text-goodseed-950">{product.name}</h3>
                <p className="mt-2 min-h-[72px] text-sm font-semibold leading-6 text-goodseed-700">{product.detail}</p>
                <div className="mt-4 flex gap-2">
                  <Badge className="bg-goodseed-50 text-goodseed-800 ring-goodseed-100">{product.status}</Badge>
                  <a href="#public-contact" className="ml-auto text-sm font-extrabold text-goodseed-700">ติดต่อ</a>
                </div>
              </article>
            ))}
          </div>
        </section>

        <section id="public-technology" className="bg-goodseed-900 py-16 text-white">
          <div className="mx-auto max-w-7xl px-4 lg:px-6">
            <PublicSectionTitle dark eyebrow="Smart Farm & Technology" title="เทคโนโลยีฟาร์มอัจฉริยะ" subtitle="ระบบข้อมูลช่วยให้เจ้าของ ผู้จัดการ และทีมงานมองเห็นสถานะฟาร์มแบบใกล้เคียง Real-time" />
            <div className="grid gap-4 md:grid-cols-3">
              {technologyItems.map((item) => (
                <div key={item} className="rounded-xl border border-white/10 bg-white/10 p-5 shadow-sm backdrop-blur">
                  <Icon name={item.includes("QR") ? "qr" : item.includes("Dashboard") ? "layout" : item.includes("Weather") ? "calendar" : "leaf"} className="h-8 w-8 text-goodseed-200" />
                  <p className="mt-4 text-lg font-extrabold">{item}</p>
                  <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-100">เชื่อมข้อมูลจากแปลง รายงาน รูปภาพ KPI และแจ้งเตือนเพื่อการตัดสินใจที่เร็วขึ้น</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        <section id="public-esg" className="mx-auto max-w-7xl px-4 py-16 lg:px-6">
          <PublicSectionTitle eyebrow="Sustainability / ESG" title="เกษตรยั่งยืนและความรับผิดชอบต่อสิ่งแวดล้อม" subtitle="GOODSEED Farm ให้ความสำคัญกับการฟื้นฟูดิน ลดการใช้สารเคมี ระบบน้ำ โครงข่ายกระจายน้ำภายในฟาร์ม พืชคลุมดิน และการหมุนเวียนทรัพยากรในฟาร์ม" />
          <div className="grid items-start gap-8 lg:grid-cols-[42%_58%] xl:gap-10">
            <div className="overflow-hidden rounded-[24px] border border-goodseed-100 bg-white p-2 shadow-soft">
              <div className="grid place-items-center rounded-[20px] bg-goodseed-50 p-3">
                <img
                  src={aboutImages.sustainable}
                  alt="Sustainable farming"
                  className="h-auto w-full rounded-[18px] object-contain"
                />
              </div>
              <div className="p-5 sm:p-7">
                <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-goodseed-600">Sustainability / ESG</p>
                <h3 className="mt-2 text-3xl font-extrabold leading-tight text-goodseed-950">GOODSEED Farm</h3>
                <p className="mt-3 max-w-md text-sm font-semibold leading-7 text-goodseed-700">
                  ระบบเกษตรยั่งยืนที่เชื่อมโยงการฟื้นฟูดิน การจัดการน้ำ และการหมุนเวียนทรัพยากรในฟาร์ม
                </p>
              </div>
            </div>
            <div className="grid gap-6 sm:grid-cols-2">
              {esgTopics.map((item) => (
                <article key={item.title} className="flex min-h-[188px] flex-col rounded-[24px] border border-goodseed-100/80 bg-white p-7 shadow-sm transition hover:-translate-y-0.5 hover:shadow-soft">
                  <Icon name="leaf" className="h-8 w-8 text-goodseed-700" />
                  <h3 className="mt-5 text-2xl font-extrabold leading-snug text-goodseed-950 sm:text-[28px]">{item.title}</h3>
                  <p className="mt-3 text-[15px] font-semibold leading-7 text-goodseed-700 sm:text-base">{item.detail}</p>
                </article>
              ))}
            </div>
          </div>
        </section>

        <section id="public-news" className="bg-goodseed-50 py-16">
          <div className="mx-auto max-w-7xl px-4 lg:px-6">
            <PublicSectionTitle eyebrow="News & Activities" title="ข่าวสาร กิจกรรม และประกาศฟาร์ม" subtitle="พื้นที่สำหรับอัปเดตข่าวฟาร์ม โปรโมชั่นสินค้า สินค้าใหม่ ผลผลิตพร้อมขาย กิจกรรม บทความ และ CSR" />
            {canManagePublicMedia && (
              <div className="mb-6 rounded-[24px] border border-goodseed-100 bg-white p-4 shadow-sm md:p-5">
                <div className="mb-4 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.18em] text-goodseed-500">Web Admin</p>
                    <h3 className="mt-1 text-xl font-black text-goodseed-950">จัดการรูปข่าวสารและกิจกรรม</h3>
                    <p className="mt-1 text-sm font-bold text-goodseed-600">ผู้ดูแลเว็บสามารถเพิ่มหรือลบรูปข่าว กิจกรรม และประกาศฟาร์มได้</p>
                  </div>
                  <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{newsItems.length} รายการ</Badge>
                </div>
                <form onSubmit={addNewsItem} className="grid gap-3 lg:grid-cols-[0.9fr_1fr_0.8fr_1.4fr_1.3fr_auto]">
                  <input value={newsDraft.type} onChange={(event) => setNewsDraft((current) => ({ ...current, type: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="ประเภทข่าว" aria-label="ประเภทข่าว" />
                  <input value={newsDraft.title} onChange={(event) => setNewsDraft((current) => ({ ...current, title: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="หัวข้อข่าว" aria-label="หัวข้อข่าว" />
                  <input value={newsDraft.date} onChange={(event) => setNewsDraft((current) => ({ ...current, date: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="วันที่" aria-label="วันที่ข่าว" />
                  <input value={newsDraft.image} onChange={(event) => setNewsDraft((current) => ({ ...current, image: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="/public/farm-assets/example.jpg" aria-label="URL หรือ public path รูปข่าว" />
                  <input value={newsDraft.summary} onChange={(event) => setNewsDraft((current) => ({ ...current, summary: event.target.value }))} className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500" placeholder="รายละเอียดข่าว" aria-label="รายละเอียดข่าว" />
                  <button type="submit" className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-black text-white transition hover:bg-goodseed-800">
                    <Icon name="plus" className="h-4 w-4" />เพิ่มข่าว
                  </button>
                </form>
              </div>
            )}
            <div className="grid gap-5 md:grid-cols-3">
              {newsItems.map((item) => (
                <article key={item.id} className="flex h-full flex-col overflow-hidden rounded-2xl border border-goodseed-100 bg-white p-4 shadow-soft">
                  <button
                    type="button"
                    onClick={() => setZoomImage({ title: item.title, detail: item.summary, src: item.image })}
                    className="grid w-full shrink-0 place-items-center rounded-xl bg-goodseed-50 p-2 transition hover:bg-goodseed-100"
                    style={{ height: 260, overflow: "hidden" }}
                  >
                    <img
                      src={item.image}
                      alt={item.title}
                      style={{ display: "block", maxHeight: "100%", maxWidth: "100%", objectFit: "contain" }}
                    />
                  </button>
                  <div className="relative z-10 flex flex-1 flex-col bg-white pt-4">
                    <div className="flex items-center justify-between gap-3">
                      <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{item.type}</Badge>
                      <span className="text-xs font-bold text-goodseed-500">{item.date}</span>
                    </div>
                    <h3 className="mt-3 text-lg font-extrabold text-goodseed-950">{item.title}</h3>
                    <p className="mt-2 flex-1 text-sm font-semibold leading-7 text-goodseed-700">{item.summary}</p>
                    <div className="mt-4 flex flex-wrap gap-2">
                      <button type="button" onClick={() => setDetailItem({ kind: "news", title: item.title, category: item.type, image: item.image, date: item.date, description: item.summary })} className="inline-flex min-h-10 items-center justify-center rounded-xl border border-goodseed-200 px-4 py-2 text-xs font-black text-goodseed-800 transition hover:bg-goodseed-50">ดูรายละเอียด</button>
                      <button type="button" onClick={() => setZoomImage({ title: item.title, detail: item.summary, src: item.image })} className="inline-flex min-h-10 items-center justify-center rounded-xl bg-goodseed-50 px-4 py-2 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100 transition hover:bg-goodseed-100">ซูมรูป</button>
                      {canManagePublicMedia && (
                        <button type="button" onClick={() => removeNewsItem(item.id)} className="inline-flex min-h-10 items-center justify-center rounded-xl bg-red-50 px-4 py-2 text-xs font-black text-red-700 ring-1 ring-red-100 transition hover:bg-red-100">ลบรูป</button>
                      )}
                    </div>
                  </div>
                </article>
              ))}
            </div>
          </div>
        </section>

        <section id="public-gallery" className="bg-white py-16">
          <div className="mx-auto max-w-7xl px-4 lg:px-6">
            <PublicSectionTitle eyebrow="Gallery / Media" title="ภาพฟาร์มและสื่อประชาสัมพันธ์" subtitle="ภาพหลักสำหรับสื่อประชาสัมพันธ์ เว็บไซต์ และ Company Profile ของ GOODSEED Farm" />
            {canManagePublicMedia && (
              <div className="rounded-[24px] border border-goodseed-100 bg-goodseed-50 p-4 shadow-sm md:p-5">
                <div className="mb-4 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.18em] text-goodseed-500">Web Admin</p>
                    <h3 className="mt-1 text-xl font-black text-goodseed-950">จัดการรูปภาพ Gallery</h3>
                  </div>
                  <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{galleryItems.length} รูป</Badge>
                </div>
                <form onSubmit={addGalleryItem} className="grid gap-3 lg:grid-cols-[1fr_0.8fr_1.4fr_auto]">
                  <input
                    value={galleryDraft.title}
                    onChange={(event) => setGalleryDraft((current) => ({ ...current, title: event.target.value }))}
                    className="rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500"
                    placeholder="ชื่อรูปภาพ"
                    aria-label="ชื่อรูปภาพ"
                  />
                  <input
                    value={galleryDraft.category}
                    onChange={(event) => setGalleryDraft((current) => ({ ...current, category: event.target.value }))}
                    className="rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500"
                    placeholder="หมวดหมู่"
                    aria-label="หมวดหมู่"
                  />
                  <input
                    value={galleryDraft.src}
                    onChange={(event) => setGalleryDraft((current) => ({ ...current, src: event.target.value }))}
                    className="rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500"
                    placeholder="/public/gallery-media/example.jpg หรือ https://..."
                    aria-label="URL หรือ public path ของรูปภาพ"
                  />
                  <button type="submit" className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-black text-white transition hover:bg-goodseed-800">
                    <Icon name="plus" className="h-4 w-4" />เพิ่มรูปภาพ
                  </button>
                </form>
              </div>
            )}

            <div className="mt-7 grid gap-5 md:grid-cols-2 xl:grid-cols-3">
              {galleryItems.map((item, index) => (
                <article key={item.id} className={`${index === 0 ? "xl:col-span-2" : ""} overflow-hidden rounded-[24px] border border-goodseed-100 bg-white shadow-soft`}>
                  <div className={`${index === 0 ? "h-[320px] sm:h-[430px]" : "h-[260px]"} bg-goodseed-50 p-2`}>
                    <img src={item.src} alt={item.title} className="h-full w-full rounded-[18px] object-contain" />
                  </div>
                  <div className="flex items-start justify-between gap-3 p-4">
                    <div className="min-w-0">
                      <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-100">{item.category}</Badge>
                      <h3 className="mt-3 text-lg font-black leading-snug text-goodseed-950">{item.title}</h3>
                    </div>
                    {canManagePublicMedia && (
                      <button
                        type="button"
                        onClick={() => removeGalleryItem(item.id)}
                        className="inline-flex shrink-0 items-center gap-1 rounded-xl bg-red-50 px-3 py-2 text-xs font-black text-red-700 ring-1 ring-red-100 transition hover:bg-red-100"
                        aria-label={`ลบรูป ${item.title}`}
                      >
                        <Icon name="trash" className="h-4 w-4" />ลบ
                      </button>
                    )}
                  </div>
                </article>
              ))}
            </div>

            <p className="mt-6 rounded-[24px] border border-goodseed-100 bg-goodseed-50 p-6 text-base font-semibold leading-8 text-goodseed-800 shadow-sm md:text-lg md:leading-9">
              GoodSeed Farm คือฟาร์มไม้ล้อมและเกษตรผสมผสานสมัยใหม่ ที่มุ่งเน้นการพัฒนาระบบการปลูก การจัดการฟาร์ม และความยั่งยืนของระบบนิเวศ เพื่อสร้างมาตรฐานใหม่ของอุตสาหกรรมไม้ล้อมไทย
            </p>
          </div>
        </section>

        <section id="public-company-profile" className="bg-goodseed-950 py-16 text-white">
          <PublicDownloadCenter role={role} />
        </section>

        <section id="public-contact" className="mx-auto max-w-7xl px-4 py-16 lg:px-6">
          <PublicSectionTitle eyebrow={t("contact.eyebrow")} title={t("contact.title")} subtitle={t("contact.subtitle")} />
          <div className="rounded-3xl border border-goodseed-100 bg-goodseed-50 p-4 shadow-soft sm:p-6 lg:p-8">
            <div className="mb-6">
              <Badge className="bg-white text-goodseed-800 ring-goodseed-200">{t("contact.mapBadge")}</Badge>
              <h3 className="mt-3 text-3xl font-extrabold leading-tight text-goodseed-950">{t("contact.mapTitle")}</h3>
              <p className="mt-2 max-w-3xl text-sm font-semibold leading-7 text-goodseed-700">{t("contact.mapSubtitle")}</p>
            </div>
            <div className="grid gap-6 lg:grid-cols-[0.9fr_1.1fr]">
              <div className="order-2 rounded-2xl border border-goodseed-100 bg-white p-5 shadow-sm lg:order-1 lg:p-6">
                <div className="flex items-start gap-4">
                  <div className="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-goodseed-100 text-goodseed-800">
                    <Icon name="map" className="h-6 w-6" />
                  </div>
                  <div>
                    <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-goodseed-500">{t("contact.contactInformation")}</p>
                    <h4 className="mt-1 text-2xl font-extrabold text-goodseed-950">GOODSEED Farm</h4>
                    <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{t("contact.address")}</p>
                  </div>
                </div>
                <div className="mt-6 grid gap-3 text-sm font-bold text-goodseed-800">
                  <div className="rounded-xl bg-goodseed-50 p-4">
                    <p className="text-xs font-extrabold text-goodseed-500">Business Hours</p>
                    <p className="mt-1">{t("contact.businessHours")}</p>
                  </div>
                  <div className="grid gap-3 sm:grid-cols-2">
                    <div className="rounded-xl bg-goodseed-50 p-4"><p className="text-xs font-extrabold text-goodseed-500">Phone</p><p className="mt-1">08x-xxx-xxxx</p></div>
                    <div className="rounded-xl bg-goodseed-50 p-4"><p className="text-xs font-extrabold text-goodseed-500">Email</p><p className="mt-1">contact@goodseedfarm.local</p></div>
                    <div className="rounded-xl bg-goodseed-50 p-4"><p className="text-xs font-extrabold text-goodseed-500">Line</p><p className="mt-1">@goodseedfarm</p></div>
                    <div className="rounded-xl bg-goodseed-50 p-4"><p className="text-xs font-extrabold text-goodseed-500">Facebook</p><p className="mt-1">GoodSeed Farm</p></div>
                  </div>
                </div>
                <div className="mt-6 grid gap-3 sm:grid-cols-2">
                  <a href={goodSeedMapsLink} target="_blank" rel="noopener noreferrer" className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl border border-goodseed-200 bg-white px-5 py-3 text-sm font-extrabold text-goodseed-800 shadow-sm transition hover:bg-goodseed-50">
                    <Icon name="map" className="h-4 w-4" />
                    {t("actions.openGoogleMaps")}
                  </a>
                  <a href={goodSeedMapsLink} target="_blank" rel="noopener noreferrer" className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-sm transition hover:bg-goodseed-800">
                    <Icon name="map" className="h-4 w-4" />
                    {t("actions.directionsToFarm")}
                  </a>
                </div>
              </div>
              <div className="order-1 overflow-hidden rounded-2xl border border-goodseed-100 bg-white p-4 shadow-sm lg:order-2">
                <div className="relative grid min-h-[360px] place-items-center overflow-hidden rounded-xl bg-gradient-to-br from-goodseed-900 via-goodseed-700 to-goodseed-400 p-6 text-center text-white">
                  <div className="absolute inset-0 opacity-25">
                    <img src={farmMapImages[0].src} alt="GOODSEED Farm location preview" className="h-full w-full object-cover" />
                  </div>
                  <div className="relative max-w-md">
                    <div className="mx-auto grid h-16 w-16 place-items-center rounded-2xl bg-white/15 backdrop-blur">
                      <Icon name="map" className="h-9 w-9 text-white" />
                    </div>
                    <h4 className="mt-5 text-3xl font-extrabold">{t("contact.locationTitle")}</h4>
                    <p className="mt-3 text-sm font-semibold leading-7 text-goodseed-50">{t("contact.locationText")}</p>
                    <a href={goodSeedMapsLink} target="_blank" rel="noopener noreferrer" className="mt-6 inline-flex min-h-12 items-center justify-center rounded-xl bg-white px-6 py-3 text-sm font-extrabold text-goodseed-900 shadow-soft transition hover:bg-goodseed-50">{t("actions.openMapsEn")}</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className="mt-8 grid gap-6 lg:grid-cols-[0.8fr_1.2fr]">
            <div className="rounded-2xl border border-goodseed-100 bg-white p-6 shadow-soft">
              <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-goodseed-500">Visit & Partnership</p>
              <h3 className="mt-2 text-2xl font-extrabold text-goodseed-950">{t("contact.visitTitle")}</h3>
              <p className="mt-3 text-sm font-semibold leading-7 text-goodseed-700">{t("contact.visitText")}</p>
              <a href={goodSeedMapsLink} target="_blank" rel="noopener noreferrer" className="mt-5 inline-flex w-full min-h-12 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-sm transition hover:bg-goodseed-800">
                <Icon name="map" className="h-4 w-4" />
                {t("actions.directions")}
              </a>
            </div>
            <form className="rounded-2xl border border-goodseed-100 bg-white p-6 shadow-soft">
              <div className="grid gap-4 sm:grid-cols-2">
                {[t("contact.name"), t("contact.company"), t("contact.email"), t("contact.phone")].map((label) => (
                  <label key={label} className="text-sm font-extrabold text-goodseed-900">{label}<input className="mt-2 w-full rounded-lg border border-goodseed-100 px-3 py-3 outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" /></label>
                ))}
              </div>
              <label className="mt-4 block text-sm font-extrabold text-goodseed-900">{t("contact.message")}<textarea rows="5" className="mt-2 w-full rounded-lg border border-goodseed-100 px-3 py-3 outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" /></label>
              <button type="button" className="mt-5 rounded-lg bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-sm">{t("actions.sendMessage")}</button>
            </form>
          </div>
        </section>
      </main>
      {waitlistProduct && (
        <div className="fixed inset-0 z-[80] grid place-items-center bg-goodseed-950/65 px-4 py-6 backdrop-blur-sm" role="dialog" aria-modal="true">
          <div className="w-full max-w-2xl overflow-hidden rounded-3xl bg-white shadow-2xl">
            <div className="flex items-start justify-between gap-4 border-b border-goodseed-100 bg-goodseed-50 p-6">
              <div>
                <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-goodseed-500">Customer Waitlist</p>
                <h3 className="mt-2 text-2xl font-extrabold text-goodseed-950">แจ้งเตือนเมื่อเปิดขาย</h3>
                <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{waitlistProduct.name}</p>
              </div>
              <button type="button" onClick={() => setWaitlistProduct(null)} className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-white text-goodseed-700 shadow-sm hover:bg-goodseed-100" aria-label="Close waitlist form">
                <Icon name="x" className="h-5 w-5" />
              </button>
            </div>
            <form className="grid gap-4 p-6 sm:grid-cols-2">
              <label className="text-sm font-extrabold text-goodseed-900">ชื่อ<input className="mt-2 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" /></label>
              <label className="text-sm font-extrabold text-goodseed-900">เบอร์โทร<input className="mt-2 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" /></label>
              <label className="text-sm font-extrabold text-goodseed-900">Email<input className="mt-2 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" /></label>
              <label className="text-sm font-extrabold text-goodseed-900">สินค้าที่สนใจ<input value={waitlistProduct.name} readOnly className="mt-2 w-full rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-semibold text-goodseed-800 outline-none" /></label>
              <label className="sm:col-span-2 text-sm font-extrabold text-goodseed-900">หมายเหตุ<textarea rows="4" className="mt-2 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="ช่องทางติดต่อหรือจำนวนที่สนใจ" /></label>
              <div className="flex flex-col gap-3 sm:col-span-2 sm:flex-row sm:justify-end">
                <button type="button" onClick={() => setWaitlistProduct(null)} className="rounded-xl border border-goodseed-200 px-5 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50">ปิด</button>
                <button type="button" onClick={() => setWaitlistProduct(null)} className="rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-sm hover:bg-goodseed-800">บันทึกความสนใจ</button>
              </div>
            </form>
          </div>
        </div>
      )}
      {detailItem && (
        <div className="fixed inset-0 z-[85] grid place-items-center bg-goodseed-950/70 px-4 py-6 backdrop-blur-sm" role="dialog" aria-modal="true" aria-label={`รายละเอียด ${detailItem.title}`}>
          <div className="flex max-h-[92vh] w-full max-w-4xl flex-col overflow-hidden rounded-3xl bg-white shadow-2xl">
            <div className="flex items-start justify-between gap-4 border-b border-goodseed-100 bg-goodseed-50 p-5">
              <div className="min-w-0">
                <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{detailItem.category}</Badge>
                <h3 className="mt-3 text-2xl font-black leading-tight text-goodseed-950">{detailItem.title}</h3>
                {detailItem.date && <p className="mt-1 text-sm font-bold text-goodseed-500">{detailItem.date}</p>}
              </div>
              <button type="button" onClick={() => setDetailItem(null)} className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-white text-goodseed-700 shadow-sm hover:bg-goodseed-100" aria-label="ปิดรายละเอียด">
                <Icon name="x" className="h-5 w-5" />
              </button>
            </div>
            <div className="thin-scrollbar overflow-auto p-5">
              <button type="button" onClick={() => setZoomImage({ title: detailItem.title, detail: detailItem.description, src: detailItem.image })} className="grid max-h-[430px] min-h-[240px] w-full place-items-center rounded-2xl bg-goodseed-50 p-3 ring-1 ring-goodseed-100 transition hover:bg-goodseed-100">
                <img src={detailItem.image} alt={detailItem.title} className="max-h-[400px] max-w-full object-contain" />
              </button>
              <p className="mt-5 text-base font-semibold leading-8 text-goodseed-800">{detailItem.description}</p>
              {detailItem.features?.length > 0 && (
                <div className="mt-5 flex flex-wrap gap-2">
                  {detailItem.features.map((feature) => (
                    <span key={feature} className="rounded-full bg-goodseed-50 px-3 py-1 text-xs font-extrabold text-goodseed-700 ring-1 ring-goodseed-100">{feature}</span>
                  ))}
                </div>
              )}
              <div className="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-end">
                <button type="button" onClick={() => setZoomImage({ title: detailItem.title, detail: detailItem.description, src: detailItem.image })} className="inline-flex min-h-11 items-center justify-center rounded-xl border border-goodseed-200 px-5 py-3 text-sm font-black text-goodseed-800 transition hover:bg-goodseed-50">ซูมรูป</button>
                <button type="button" onClick={() => setDetailItem(null)} className="inline-flex min-h-11 items-center justify-center rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-black text-white transition hover:bg-goodseed-800">ปิดรายละเอียด</button>
              </div>
            </div>
          </div>
        </div>
      )}
      {zoomImage && (
        <div className="fixed inset-0 z-[90] grid place-items-center bg-goodseed-950/80 p-3 backdrop-blur-sm" role="dialog" aria-modal="true" aria-label={`ซูมดู ${zoomImage.title}`}>
          <div className="flex max-h-[94vh] w-full max-w-7xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
            <div className="flex items-start justify-between gap-4 border-b border-goodseed-100 p-4">
              <div className="min-w-0">
                <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-100">Zoom Preview</Badge>
                <h3 className="mt-2 text-xl font-black text-goodseed-950">{zoomImage.title}</h3>
                {zoomImage.detail && <p className="mt-1 text-sm font-bold text-goodseed-700">{zoomImage.detail}</p>}
              </div>
              <button type="button" onClick={() => setZoomImage(null)} className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-goodseed-50 text-goodseed-800 ring-1 ring-goodseed-100" aria-label="ปิดหน้าซูม">
                <Icon name="x" className="h-5 w-5" />
              </button>
            </div>
            <div className="thin-scrollbar flex-1 overflow-auto bg-goodseed-50 p-4">
              <img src={zoomImage.src} alt={zoomImage.title} className="mx-auto h-auto max-h-none max-w-full object-contain" />
            </div>
          </div>
        </div>
      )}
      <footer className="border-t border-goodseed-100 bg-goodseed-950 px-4 py-8 text-white lg:px-6">
        <div className="mx-auto grid max-w-7xl gap-6 md:grid-cols-[1fr_auto] md:items-center">
          <div>
            <p className="text-xl font-extrabold">GOODSEED Farm</p>
            <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-100">โคกแสมสาร, โคกเจริญ, ลพบุรี | contact@goodseedfarm.local | Line: @goodseedfarm</p>
          </div>
          <div className="flex flex-col gap-3 sm:flex-row">
            <a href="#public-contact" className="inline-flex min-h-11 items-center justify-center rounded-xl border border-white/20 px-5 py-2 text-sm font-extrabold text-white hover:bg-white/10">{t("actions.contact")}</a>
            <a href={goodSeedMapsLink} target="_blank" rel="noopener noreferrer" className="inline-flex min-h-11 items-center justify-center gap-2 rounded-xl bg-white px-5 py-2 text-sm font-extrabold text-goodseed-900 hover:bg-goodseed-50">
              <Icon name="map" className="h-4 w-4" />
              {t("actions.directions")}
            </a>
          </div>
        </div>
      </footer>
      <a href={goodSeedMapsLink} target="_blank" rel="noopener noreferrer" className="fixed bottom-5 right-5 z-50 inline-flex min-h-14 items-center justify-center gap-2 rounded-full bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-2xl ring-4 ring-white/70 md:hidden">
        <Icon name="map" className="h-5 w-5" />
        {t("actions.directions")}
      </a>
    </div>
  );
}

function LoginPage({ onLogin, onPublic, language, setLanguage, t }) {
  const [authMode, setAuthMode] = useState("login");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [signupForm, setSignupForm] = useState({
    fullName: "",
    phone: "",
    email: "",
    requestedRole: "staff",
    password: "",
    confirmPassword: "",
    requestNote: "",
  });
  const [message, setMessage] = useState("");
  const [isAuthLoading, setIsAuthLoading] = useState(false);
  const signupRoleOptions = ownerManagedRoleOptions.filter((option) => option.id !== "owner");
  const updateSignupForm = (field, value) => setSignupForm((current) => ({ ...current, [field]: value }));
  const submitLogin = async (event) => {
    event.preventDefault();
    if (!username.trim() || !password.trim()) {
      setMessage(t("login.emptyError"));
      return;
    }
    setIsAuthLoading(true);
    setMessage("");
    try {
      const email = await resolveLoginIdentifier(username);
      const { data, error } = await signInWithPasswordDirect(email, password);
      if (error) {
        setMessage(supabaseAuthMessage(error));
        return;
      }
      const accessToken = data.session?.access_token;
      const profile = await withSupabaseTimeout(loadSupabaseProfileDirect(data.user, accessToken), "profile-timeout", 12000);
      if (!canEnterBackend(profile)) {
        onLogin(profile);
        return;
      }
      onLogin(profile);
    } catch (error) {
      setMessage(supabaseAuthMessage(error));
    } finally {
      setIsAuthLoading(false);
    }
  };
  const submitSignup = async (event) => {
    event.preventDefault();
    const email = signupForm.email.trim().toLowerCase();
    if (!signupForm.fullName.trim() || !email || !signupForm.password.trim()) {
      setMessage("กรุณากรอกชื่อ อีเมล และรหัสผ่าน / Please enter name, email and password.");
      return;
    }
    if (signupForm.password.length < 6) {
      setMessage("รหัสผ่านต้องมีอย่างน้อย 6 ตัวอักษร / Password must be at least 6 characters.");
      return;
    }
    if (signupForm.password !== signupForm.confirmPassword) {
      setMessage("รหัสผ่านและยืนยันรหัสผ่านไม่ตรงกัน / Password confirmation does not match.");
      return;
    }
    setIsAuthLoading(true);
    setMessage("");
    try {
      const { data, error } = await signUpWithPasswordDirect({
        email,
        password: signupForm.password,
        fullName: signupForm.fullName,
        phone: signupForm.phone,
        requestedRole: signupForm.requestedRole,
        requestNote: signupForm.requestNote,
      });
      if (error) {
        setMessage(supabaseAuthMessage(error));
        return;
      }
      if (data?.session?.user) {
        const profile = await withSupabaseTimeout(loadSupabaseProfileDirect(data.session.user, data.session.access_token), "profile-timeout");
        onLogin(profile);
        return;
      }
      setMessage("สมัครสมาชิกสำเร็จแล้ว กรุณายืนยันอีเมลถ้าระบบส่งอีเมลยืนยัน จากนั้นแจ้ง Owner ให้อนุมัติสิทธิ์ใน User Management / Sign-up submitted. Please confirm email if required, then wait for Owner approval.");
      setAuthMode("login");
      setUsername(email);
      setPassword("");
    } catch (error) {
      setMessage(supabaseAuthMessage(error));
    } finally {
      setIsAuthLoading(false);
    }
  };
  return (
    <div className="grid min-h-screen place-items-center bg-goodseed-950 px-4 py-10">
      <div className="absolute inset-0 opacity-35">
        <img src={homeHeroImage} alt="GoodSeed Farm" className="h-full w-full object-cover" />
      </div>
      <div className="absolute inset-0 bg-gradient-to-r from-goodseed-950/90 via-goodseed-950/70 to-goodseed-900/40" />
      <div className="absolute right-4 top-4 z-10">
        <LanguageToggle language={language} setLanguage={setLanguage} />
      </div>
      <div className="relative grid w-full max-w-6xl items-center gap-8 lg:grid-cols-[0.92fr_0.58fr]">
        <div className="hidden text-white lg:block">
          <Badge className="bg-white/12 text-white ring-white/20">{t("login.internalLabel")}</Badge>
          <h1 className="mt-6 max-w-2xl text-5xl font-extrabold leading-tight">{t("login.operationCenter")}</h1>
          <p className="mt-5 max-w-xl text-base font-semibold leading-8 text-goodseed-100">
            {t("login.operationText")}
          </p>
          <button onClick={onPublic} className="mt-8 rounded-lg border border-white/30 px-5 py-3 text-sm font-extrabold text-white hover:bg-white/10">{t("actions.backToWebsite")}</button>
        </div>
        <div className="rounded-3xl border border-white/20 bg-white/95 p-6 shadow-2xl backdrop-blur-xl sm:p-8 lg:p-10">
          <div className="text-center">
            <img src={farmLogo} alt="GoodSeed Farm" className="mx-auto h-20 w-20 rounded-2xl object-cover ring-1 ring-goodseed-100" />
            <h2 className="mt-5 text-3xl font-extrabold text-goodseed-950">{t("login.title")}</h2>
            <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{t("login.subtitle")}</p>
            <Badge className="mt-3 bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Supabase Auth / Email + Password</Badge>
          </div>
          <div className="mt-7 grid grid-cols-2 gap-1 rounded-2xl bg-goodseed-50 p-1">
            <button type="button" onClick={() => { setAuthMode("login"); setMessage(""); }} className={`rounded-xl px-4 py-3 text-sm font-extrabold transition ${authMode === "login" ? "bg-white text-goodseed-950 shadow-sm" : "text-goodseed-700 hover:bg-white/60"}`}>Login / เข้าสู่ระบบ</button>
            <button type="button" onClick={() => { setAuthMode("signup"); setMessage(""); }} className={`rounded-xl px-4 py-3 text-sm font-extrabold transition ${authMode === "signup" ? "bg-white text-goodseed-950 shadow-sm" : "text-goodseed-700 hover:bg-white/60"}`}>Sign Up / สมัครสมาชิก</button>
          </div>
          <p className="mt-3 rounded-xl bg-goodseed-50 px-4 py-3 text-xs font-bold leading-6 text-goodseed-700">
            {authMode === "login"
              ? "ทีมงานที่มีบัญชีแล้วสามารถเข้าสู่ระบบได้ทันที / Existing team accounts can login here."
              : "หุ้นส่วนและทีมงานสมัครเองได้ จากนั้น Owner จะอนุมัติสิทธิ์ใน User Management / Team members can register and wait for Owner approval."}
          </p>
          {authMode === "login" ? <form onSubmit={submitLogin} className="mt-6 space-y-4">
              <label className="block text-sm font-extrabold text-goodseed-900">
                {t("login.email")}
                <input value={username} onChange={(event) => setUsername(event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="" />
              </label>
              <label className="block text-sm font-extrabold text-goodseed-900">
                {t("login.password")}
                <input value={password} onChange={(event) => setPassword(event.target.value)} type="password" className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="••••••••" />
              </label>
              {message && <div className="rounded-lg bg-amber-50 px-4 py-3 text-sm font-bold text-amber-800">{message}</div>}
              <button type="submit" disabled={isAuthLoading} className="w-full rounded-xl bg-goodseed-700 px-5 py-4 text-base font-extrabold text-white shadow-soft transition hover:bg-goodseed-800 disabled:cursor-not-allowed disabled:bg-goodseed-300">{isAuthLoading ? "กำลังตรวจสอบ..." : t("actions.login")}</button>
              <div className="flex items-center justify-between gap-3 text-xs font-bold text-goodseed-700">
                <button type="button" className="hover:text-goodseed-900">{t("actions.forgotPassword")}</button>
                <span>{t("login.roleAssigned")}</span>
              </div>
              <div className="rounded-xl bg-goodseed-50 p-4 text-xs font-semibold leading-6 text-goodseed-700">
                เพื่อความปลอดภัย ระบบไม่แสดงอีเมลหรือรหัสผ่านตัวอย่างบนหน้าเว็บ
              </div>
              <button type="button" onClick={onPublic} className="w-full rounded-xl border border-goodseed-200 px-5 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50 lg:hidden">{t("actions.backToWebsite")}</button>
          </form> : <form onSubmit={submitSignup} className="mt-6 space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <label className="block text-sm font-extrabold text-goodseed-900">
                  Full Name / ชื่อ-นามสกุล
                  <input value={signupForm.fullName} onChange={(event) => updateSignupForm("fullName", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" />
                </label>
                <label className="block text-sm font-extrabold text-goodseed-900">
                  Phone / เบอร์โทร
                  <input value={signupForm.phone} onChange={(event) => updateSignupForm("phone", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" />
                </label>
              </div>
              <label className="block text-sm font-extrabold text-goodseed-900">
                Email / Username
                <input type="email" value={signupForm.email} onChange={(event) => updateSignupForm("email", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" />
              </label>
              <label className="block text-sm font-extrabold text-goodseed-900">
                Requested Role / สิทธิ์ที่ต้องการขอ
                <select value={signupForm.requestedRole} onChange={(event) => updateSignupForm("requestedRole", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100">
                  {signupRoleOptions.map((option) => <option key={option.id} value={option.id}>{option.label} / {option.th}</option>)}
                  <option value="customer">Customer / ลูกค้า</option>
                </select>
              </label>
              <div className="grid gap-4 sm:grid-cols-2">
                <label className="block text-sm font-extrabold text-goodseed-900">
                  Password / รหัสผ่าน
                  <input type="password" value={signupForm.password} onChange={(event) => updateSignupForm("password", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="••••••••" />
                </label>
                <label className="block text-sm font-extrabold text-goodseed-900">
                  Confirm / ยืนยันรหัสผ่าน
                  <input type="password" value={signupForm.confirmPassword} onChange={(event) => updateSignupForm("confirmPassword", event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="••••••••" />
                </label>
              </div>
              <label className="block text-sm font-extrabold text-goodseed-900">
                Request Note / เหตุผลหรือหน่วยงาน
                <textarea value={signupForm.requestNote} onChange={(event) => updateSignupForm("requestNote", event.target.value)} rows="3" className="mt-2 w-full resize-none rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" />
              </label>
              {message && <div className="rounded-lg bg-amber-50 px-4 py-3 text-sm font-bold text-amber-800">{message}</div>}
              <button type="submit" disabled={isAuthLoading} className="w-full rounded-xl bg-goodseed-700 px-5 py-4 text-base font-extrabold text-white shadow-soft transition hover:bg-goodseed-800 disabled:cursor-not-allowed disabled:bg-goodseed-300">{isAuthLoading ? "กำลังสมัคร..." : "Create Account / สมัครสมาชิก"}</button>
              <button type="button" onClick={onPublic} className="w-full rounded-xl border border-goodseed-200 px-5 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50 lg:hidden">{t("actions.backToWebsite")}</button>
          </form>}
        </div>
      </div>
    </div>
  );
}

function AuthStatusPage({ profile, onPublic, onSignOut }) {
  const status = profile?.disabled ? "disabled" : profile?.approvalStatus || "pending";
  const isPending = isPendingApprovalStatus(status);
  const statusTitle = profile?.disabled
    ? "บัญชีถูกปิดการใช้งาน"
    : status === "rejected"
      ? "บัญชีไม่ได้รับอนุมัติ"
      : isPending
        ? "รอ Owner อนุมัติ"
        : "บัญชีนี้ยังเข้า Backend ไม่ได้";
  const statusDetail = backendAccessBlockMessage(profile);
  const debugRows = [
    ["Current User ID", profile?.id || "-"],
    ["Current User Email", profile?.email || "-"],
    ["Current Profile Status", status],
    ["Current Role", profile?.role || "-"],
    ["Requested Role", profile?.requestedRole || "-"],
    ["Last Login Error", statusDetail],
  ];

  return (
    <div className="grid min-h-screen place-items-center bg-goodseed-950 px-4 py-10">
      <div className="absolute inset-0 opacity-25">
        <img src={homeHeroImage} alt="GoodSeed Farm" className="h-full w-full object-cover" />
      </div>
      <div className="absolute inset-0 bg-gradient-to-br from-goodseed-950/95 via-goodseed-950/82 to-goodseed-800/55" />
      <section className="relative w-full max-w-3xl rounded-3xl border border-white/20 bg-white/95 p-6 text-center shadow-2xl backdrop-blur-xl sm:p-8">
        <img src={farmLogo} alt="GoodSeed Farm" className="mx-auto h-20 w-20 rounded-2xl object-cover ring-1 ring-goodseed-100" />
        <Badge className={`mt-5 ${isPending ? "bg-amber-100 text-amber-800 ring-amber-200" : status === "rejected" || profile?.disabled ? "bg-red-100 text-red-700 ring-red-200" : "bg-slate-100 text-slate-700 ring-slate-200"}`}>
          {status}
        </Badge>
        <h1 className="mt-4 text-3xl font-black text-goodseed-950">{statusTitle}</h1>
        <p className="mx-auto mt-3 max-w-2xl whitespace-pre-line text-sm font-bold leading-7 text-goodseed-700">{statusDetail}</p>
        {isPending && (
          <div className="mt-5 rounded-2xl border border-amber-100 bg-amber-50 p-4 text-left text-sm font-bold leading-7 text-amber-900">
            Flow ปัจจุบัน: ผู้ใช้สมัครสมาชิก → ระบบส่งคำขอเข้า Backend → Owner อนุมัติใน User Management → ผู้ใช้ Login เข้าใช้งานตาม Role
          </div>
        )}
        <div className="mt-6 rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4 text-left">
          <p className="text-sm font-black text-goodseed-950">Debug Panel</p>
          <div className="mt-3 grid gap-2">
            {debugRows.map(([label, value]) => (
              <div key={label} className="grid gap-1 rounded-xl bg-white p-3 text-xs font-bold text-goodseed-700 sm:grid-cols-[180px_1fr]">
                <span className="text-goodseed-500">{label}</span>
                <span className="break-words text-goodseed-900">{value}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-center">
          <button type="button" onClick={onPublic} className="rounded-xl border border-goodseed-200 bg-white px-5 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50">กลับหน้าเว็บไซต์</button>
          <button type="button" onClick={onSignOut} className="rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white hover:bg-goodseed-800">Sign Out / ออกจากระบบ</button>
        </div>
      </section>
    </div>
  );
}

function InternalModulePage({ title, subtitle, icon, cards, children }) {
  return (
    <section className="space-y-5">
      <DashboardPanel title={title} action={<Icon name={icon} className="h-7 w-7 text-goodseed-700" />}>
        <p className="text-sm font-semibold leading-7 text-goodseed-700">{subtitle}</p>
        <div className="mt-5 grid gap-3 md:grid-cols-3">
          {cards.map((card) => (
            <div key={card.title} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4">
              <p className="text-sm font-bold text-goodseed-600">{card.label}</p>
              <p className="mt-2 text-2xl font-extrabold text-goodseed-950">{card.value}</p>
              <p className="mt-1 text-xs font-semibold leading-6 text-goodseed-700">{card.title}</p>
            </div>
          ))}
        </div>
      </DashboardPanel>
      {children}
    </section>
  );
}

function FarmManagementPage({ role = "owner" }) {
  return (
    <InternalModulePage
      title="Farm Management"
      subtitle="จัดการแปลงปลูก รอบปลูก ผังแปลง ระบบน้ำ บ่อ ถนน โรงเรือน และ GPS Zone ในหน้ารวมเดียว"
      icon="map"
      cards={[
        { label: "รอบปลูก", value: "A-F", title: "วางแผนรอบปลูกและโซนขยาย" },
        { label: "พื้นที่ปลูก", value: "15 ไร่", title: "รอบปลูก A-C ที่ใช้งานปัจจุบัน" },
        { label: "โครงสร้าง", value: "7 รายการ", title: "ระบบน้ำ บ่อ ถนน โรงเรือน และโซนทดลอง" },
      ]}
    >
      <CrudGovernanceBar role={role} moduleId="farm-plots" title="Farm Plots / แปลงปลูก CRUD" />
      <FarmMapGallery />
    </InternalModulePage>
  );
}

function TreeManagementPage({ role = "owner" }) {
  return (
    <InternalModulePage
      title="Tree Management"
      subtitle="ระบบจัดการ Tree ID, QR Code, Species, Plant Date, Growth Tracking, รูปภาพ, สถานะ KPI และประวัติต้นไม้"
      icon="tree"
      cards={[
        { label: "ต้นไม้รวม", value: "3,354", title: "รอบปลูก A-C ตามผังจริง" },
        { label: "ชนิดไม้หลัก", value: "6", title: "จามจุรีทอง หางนกยูง สะเดา กัลปพฤกษ์ ปีบ มะฮอกกานี" },
        { label: "QR Tree ID", value: "พร้อมใช้", title: "รองรับประวัติการดูแลและตรวจสอบย้อนกลับ" },
      ]}
    >
      <CrudGovernanceBar role={role} moduleId="tree-database" title="Crop / Tree Database CRUD" />
      <FarmMapGallery />
    </InternalModulePage>
  );
}

const farmPlanStorageKey = "goodseed-farm-work-planning-v1";

const farmPlannerLevels = [
  { id: "yearly", label: "Yearly Plan", th: "แผนรายปี", icon: "calendar" },
  { id: "monthly", label: "Monthly Plan", th: "แผนรายเดือน", icon: "calendar" },
  { id: "weekly", label: "Weekly Plan", th: "แผนรายสัปดาห์", icon: "calendar" },
];

const farmPlannerStatuses = ["Pending", "In Progress", "Done"];

const defaultFarmPlanningTasks = {
  "yearly:2026": [
    { id: "yearly-seed-1", name: "ขยายรอบปลูก A-F", detail: "วางแผนกำลังการผลิต พื้นที่ปลูก และระบบน้ำสำหรับเป้าหมายหลังขยาย", status: "In Progress" },
    { id: "yearly-seed-2", name: "มาตรฐานข้อมูล QR Traceability", detail: "จัดโครงข้อมูลต้นไม้ แปลง และหลักฐานภาพเพื่อเชื่อมกับ Daily Report", status: "Pending" },
  ],
  "monthly:2026-05": [
    { id: "monthly-seed-1", name: "ตรวจแปลง A-C ประจำเดือน", detail: "สรุปงานดูแลต้นไม้ ระบบน้ำ โรคแมลง และวัชพืชของเดือน", status: "In Progress" },
  ],
  "weekly:2026-05-W4": [
    { id: "weekly-seed-1", name: "ตรวจระบบน้ำรอบโครงข่าย", detail: "ตรวจหัวจ่ายน้ำ แรงดัน และจุดรั่วก่อนสรุปรายงานประจำวัน", status: "Pending" },
  ],
};

function readFarmPlanningTasks() {
  try {
    const saved = window.localStorage?.getItem(farmPlanStorageKey);
    return saved ? JSON.parse(saved) : defaultFarmPlanningTasks;
  } catch (error) {
    return defaultFarmPlanningTasks;
  }
}

function FarmWorkPlanningPlanner() {
  const today = new Date();
  const [planType, setPlanType] = useState("yearly");
  const [selectedYear, setSelectedYear] = useState(String(today.getFullYear()));
  const [selectedMonth, setSelectedMonth] = useState(String(today.getMonth() + 1).padStart(2, "0"));
  const [selectedWeek, setSelectedWeek] = useState("W4");
  const [taskStore, setTaskStore] = useState(readFarmPlanningTasks);
  const [editingId, setEditingId] = useState(null);
  const [draft, setDraft] = useState({ name: "", detail: "", status: "Pending" });
  const years = ["2026", "2027", "2028", "2029", "2030"];
  const weeks = ["W1", "W2", "W3", "W4", "W5"];
  const planKey = planType === "yearly" ? `yearly:${selectedYear}` : planType === "monthly" ? `monthly:${selectedYear}-${selectedMonth}` : `weekly:${selectedYear}-${selectedMonth}-${selectedWeek}`;
  const currentTasks = taskStore[planKey] || [];
  const doneCount = currentTasks.filter((task) => task.status === "Done").length;

  useEffect(() => {
    try {
      window.localStorage?.setItem(farmPlanStorageKey, JSON.stringify(taskStore));
      window.dispatchEvent(new CustomEvent("goodseed-farm-planning-updated"));
    } catch (error) {
      console.warn("Unable to save farm work planning data", error);
    }
  }, [taskStore]);

  const resetDraft = () => {
    setDraft({ name: "", detail: "", status: "Pending" });
    setEditingId(null);
  };

  const saveTask = (event) => {
    event.preventDefault();
    if (!draft.name.trim()) return;
    const payload = {
      name: draft.name.trim(),
      detail: draft.detail.trim(),
      status: draft.status,
    };
    setTaskStore((current) => {
      const rows = current[planKey] || [];
      const nextRows = editingId
        ? rows.map((task) => task.id === editingId ? { ...task, ...payload } : task)
        : [{ id: `farm-plan-task-${Date.now()}`, ...payload }, ...rows];
      return { ...current, [planKey]: nextRows };
    });
    resetDraft();
  };

  const editTask = (task) => {
    setEditingId(task.id);
    setDraft({ name: task.name, detail: task.detail, status: task.status });
  };

  const deleteTask = (id) => {
    setTaskStore((current) => ({ ...current, [planKey]: (current[planKey] || []).filter((task) => task.id !== id) }));
    if (editingId === id) resetDraft();
  };

  return (
    <section id="daily-report-farm-work-planning" className="space-y-5">
      <div className="overflow-hidden rounded-2xl border border-goodseed-100 bg-white shadow-soft">
        <div className="grid gap-5 bg-goodseed-900 p-5 text-white lg:grid-cols-[1fr_auto] lg:items-end">
          <div>
            <Badge className="bg-white/15 text-white ring-white/20">Farm Work Planning / แผนงานฟาร์ม</Badge>
            <h2 className="mt-3 text-2xl font-black leading-tight sm:text-3xl">Planner for Yearly, Monthly & Weekly Farm Work</h2>
            <p className="mt-2 max-w-4xl text-sm font-semibold leading-7 text-goodseed-50">วางแผนงานรายปี รายเดือน และรายสัปดาห์ เพื่อเชื่อมต่อกับ Daily Report, KPI และการประเมินผลงานทีมงาน</p>
          </div>
          <div className="grid grid-cols-3 gap-2 text-center">
            {[["Tasks", currentTasks.length], ["Done", doneCount], ["Active", currentTasks.length - doneCount]].map(([label, value]) => (
              <div key={label} className="rounded-xl bg-white/10 p-3 ring-1 ring-white/15">
                <p className="text-xs font-bold text-goodseed-100">{label}</p>
                <p className="text-2xl font-black">{value}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="space-y-4 p-4">
          <div className="thin-scrollbar flex gap-2 overflow-x-auto pb-1">
            {farmPlannerLevels.map((level) => (
              <button key={level.id} type="button" onClick={() => { setPlanType(level.id); resetDraft(); }} className={`min-w-fit rounded-xl px-4 py-3 text-left text-sm font-black transition ${planType === level.id ? "bg-goodseed-700 text-white shadow-sm" : "bg-goodseed-50 text-goodseed-800 hover:bg-goodseed-100"}`}>
                {level.label}<span className="block text-xs opacity-80">{level.th}</span>
              </button>
            ))}
          </div>

          <div className="grid gap-3 rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4 md:grid-cols-3">
            <Select label="Year / ปี" value={selectedYear} onChange={setSelectedYear} options={years} />
            {(planType === "monthly" || planType === "weekly") && (
              <label><span className="text-sm font-bold text-goodseed-800">Month / เดือน</span>
                <select value={selectedMonth} onChange={(event) => setSelectedMonth(event.target.value)} className="mt-2 w-full rounded-lg border border-goodseed-200 bg-white px-3 py-2.5 text-sm text-goodseed-900 outline-none focus:ring-2 focus:ring-goodseed-300">
                  {monthNames.map((month, index) => {
                    const monthValue = String(index + 1).padStart(2, "0");
                    return <option key={monthValue} value={monthValue}>{monthValue} - {month}</option>;
                  })}
                </select>
              </label>
            )}
            {planType === "weekly" && <Select label="Week / สัปดาห์" value={selectedWeek} onChange={setSelectedWeek} options={weeks} />}
          </div>
        </div>
      </div>

      <div className="grid gap-5 xl:grid-cols-[0.9fr_1.4fr]">
        <DashboardPanel title={editingId ? "Edit Task / แก้ไขงาน" : "Add Task / เพิ่มงาน"}>
          <form onSubmit={saveTask} className="space-y-4">
            <Input label="Task Name / ชื่องาน" value={draft.name} onChange={(value) => setDraft((current) => ({ ...current, name: value }))} />
            <label className="block text-sm font-extrabold text-goodseed-900">Task Detail / รายละเอียดงาน
              <textarea value={draft.detail} onChange={(event) => setDraft((current) => ({ ...current, detail: event.target.value }))} rows="5" className="mt-2 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" />
            </label>
            <Select label="Status / สถานะงาน" value={draft.status} onChange={(value) => setDraft((current) => ({ ...current, status: value }))} options={farmPlannerStatuses} />
            <div className="flex flex-col gap-2 sm:flex-row">
              <button type="submit" className="inline-flex min-h-11 flex-1 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-black text-white shadow-sm transition hover:bg-goodseed-800">
                <Icon name={editingId ? "edit" : "plus"} className="h-4 w-4" />{editingId ? "Save Edit / บันทึกแก้ไข" : "Add / เพิ่มงาน"}
              </button>
              {editingId && <button type="button" onClick={resetDraft} className="inline-flex min-h-11 items-center justify-center rounded-xl border border-goodseed-100 bg-white px-5 py-3 text-sm font-black text-goodseed-800 hover:bg-goodseed-50">Cancel / ยกเลิก</button>}
            </div>
          </form>
        </DashboardPanel>

        <DashboardPanel title={`${farmPlannerLevels.find((level) => level.id === planType)?.label} / ${farmPlannerLevels.find((level) => level.id === planType)?.th}`}>
          <div className="mb-4 flex flex-wrap items-center gap-2">
            <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Storage: localStorage</Badge>
            <Badge className="bg-white text-goodseed-800 ring-goodseed-100">{planKey}</Badge>
          </div>
          <div className="space-y-3">
            {currentTasks.length === 0 ? (
              <div className="rounded-2xl border border-dashed border-goodseed-200 bg-goodseed-50 p-6 text-center text-sm font-bold text-goodseed-700">ยังไม่มีงานในแผนนี้ / No tasks in this plan</div>
            ) : currentTasks.map((task) => (
              <article key={task.id} className="rounded-2xl border border-goodseed-100 bg-white p-4 shadow-sm">
                <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <StatusBadge status={task.status === "Pending" ? "รอดำเนินการ" : task.status === "In Progress" ? "กำลังทำ" : "เสร็จแล้ว"} />
                      <Badge className="bg-goodseed-50 text-goodseed-800 ring-goodseed-100">{task.status}</Badge>
                    </div>
                    <h3 className="mt-3 text-xl font-black text-goodseed-950">{task.name}</h3>
                    <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{task.detail || "ไม่มีรายละเอียดเพิ่มเติม"}</p>
                  </div>
                  <div className="flex shrink-0 flex-wrap gap-2">
                    <button type="button" onClick={() => editTask(task)} className="inline-flex min-h-10 items-center gap-2 rounded-xl bg-goodseed-50 px-4 py-2 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100 hover:bg-goodseed-100"><Icon name="edit" className="h-4 w-4" />Edit / แก้ไข</button>
                    <button type="button" onClick={() => deleteTask(task.id)} className="inline-flex min-h-10 items-center gap-2 rounded-xl bg-red-50 px-4 py-2 text-xs font-black text-red-700 ring-1 ring-red-100 hover:bg-red-100"><Icon name="trash" className="h-4 w-4" />Delete / ลบ</button>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </DashboardPanel>
      </div>
    </section>
  );
}

function DailyReportPage({ onSave, role = "owner", initialSection = "report", authProfile, language = "th" }) {
  const [activeSection, setActiveSection] = useState(initialSection);
  useEffect(() => setActiveSection(initialSection), [initialSection]);

  return (
    <InternalModulePage
      title="Daily Report"
      subtitle="ตรวจแปลง ระบบน้ำ โรคแมลง วัชพืช งานประจำวัน รูปภาพ และ Google Form Integration พร้อม QR ภายในฟอร์มเดียว"
      icon="file"
      cards={[
        { label: "รายงานวันนี้", value: "2", title: "ข้อมูลส่งเข้า Dashboard ทันที" },
        { label: "QR ในฟอร์ม", value: "5 ประเภท", title: "ต้นไม้ แปลง อุปกรณ์ รถ และวัสดุ" },
        { label: "Weather Card", value: "Real-time", title: "ตำแหน่ง GoodSeed Farm เท่านั้น" },
      ]}
    >
      <CrudGovernanceBar role={role} moduleId="forms-reports" title="Forms / Reports CRUD" />
      <div className="mb-5 rounded-2xl border border-goodseed-100 bg-white p-2 shadow-sm">
        <div className="grid gap-2 sm:grid-cols-2">
          {[
            { id: "report", label: "Daily Report", th: "รายงานประจำวัน" },
            { id: "planning", label: "Farm Work Planning", th: "แผนงานฟาร์ม" },
          ].map((tab) => (
            <button key={tab.id} type="button" onClick={() => setActiveSection(tab.id)} className={`rounded-xl px-4 py-3 text-left text-sm font-black transition ${activeSection === tab.id ? "bg-goodseed-700 text-white shadow-sm" : "bg-goodseed-50 text-goodseed-800 hover:bg-goodseed-100"}`}>
              {tab.label}<span className="block text-xs opacity-80">{tab.th}</span>
            </button>
          ))}
        </div>
      </div>
      {activeSection === "report" ? (
        <div className="space-y-5">
          <ReportForm onSave={onSave} role={role} authProfile={authProfile} language={language} />
          <DailyReportCenter role={role} />
        </div>
      ) : <FarmWorkPlanningPlanner />}
    </InternalModulePage>
  );
}

const inventoryCategoryGroups = [
  { name: "วัสดุเพาะปลูกและบำรุงพืช", items: ["ปุ๋ยเม็ด", "ปุ๋ยน้ำ", "ธาตุอาหารเสริม", "ฮอร์โมนพืช", "จุลินทรีย์", "น้ำส้มควันไม้", "ไบโอชาร์", "สารปรับปรุงดิน"] },
  { name: "เมล็ดพันธุ์และต้นพันธุ์", items: ["เมล็ดพันธุ์", "กล้าไม้", "ดินปลูก"] },
  { name: "เชื้อเพลิงและพลังงาน", items: ["น้ำมันเบนซิน", "น้ำมันดีเซล"] },
  { name: "วัสดุคลุมดินและก่อสร้าง", items: ["ฟาง", "ไม้ไผ่", "ก้อนหิน", "กระสอบ"] },
  { name: "ภาชนะและวัสดุจัดเก็บ", items: ["ถุงเพาะชำ", "กระถาง", "เข่งพลาสติก"] },
  { name: "เครื่องมือและอุปกรณ์", items: ["เครื่องตัดหญ้า", "เครื่องพ่นยา", "ปั๊มน้ำ", "สายยาง", "รถเข็น", "เครื่องมือช่าง"] },
];

const inventoryMaterials = [
  { id: "MAT-001", name: "ปุ๋ยเม็ด 15-15-15", category: "วัสดุเพาะปลูกและบำรุงพืช", unit: "กก.", minimumStock: 120, unitCost: 24, lastUpdated: "27 พ.ค. 2569 09:20 น." },
  { id: "MAT-002", name: "ปุ๋ยน้ำชีวภาพ", category: "วัสดุเพาะปลูกและบำรุงพืช", unit: "ลิตร", minimumStock: 60, unitCost: 55, lastUpdated: "27 พ.ค. 2569 10:15 น." },
  { id: "MAT-003", name: "ธาตุอาหารเสริม Amino Plus", category: "วัสดุเพาะปลูกและบำรุงพืช", unit: "กก.", minimumStock: 40, unitCost: 180, lastUpdated: "26 พ.ค. 2569 16:40 น." },
  { id: "MAT-004", name: "ฮอร์โมนพืช GoodSeed", category: "วัสดุเพาะปลูกและบำรุงพืช", unit: "ลิตร", minimumStock: 30, unitCost: 220, lastUpdated: "27 พ.ค. 2569 08:10 น." },
  { id: "MAT-005", name: "จุลินทรีย์ EM", category: "วัสดุเพาะปลูกและบำรุงพืช", unit: "กก.", minimumStock: 80, unitCost: 36, lastUpdated: "24 พ.ค. 2569 13:30 น." },
  { id: "MAT-006", name: "น้ำส้มควันไม้", category: "วัสดุเพาะปลูกและบำรุงพืช", unit: "ลิตร", minimumStock: 75, unitCost: 95, lastUpdated: "27 พ.ค. 2569 11:05 น." },
  { id: "MAT-007", name: "ไบโอชาร์", category: "วัสดุเพาะปลูกและบำรุงพืช", unit: "กก.", minimumStock: 150, unitCost: 18, lastUpdated: "25 พ.ค. 2569 15:00 น." },
  { id: "MAT-008", name: "สารปรับปรุงดิน", category: "วัสดุเพาะปลูกและบำรุงพืช", unit: "กระสอบ", minimumStock: 50, unitCost: 120, lastUpdated: "23 พ.ค. 2569 17:20 น." },
  { id: "MAT-009", name: "เมล็ดพันธุ์ถั่วบราซิล", category: "เมล็ดพันธุ์และต้นพันธุ์", unit: "กก.", minimumStock: 25, unitCost: 260, lastUpdated: "27 พ.ค. 2569 09:45 น." },
  { id: "MAT-010", name: "กล้าไม้จามจุรีทอง", category: "เมล็ดพันธุ์และต้นพันธุ์", unit: "ถาด", minimumStock: 20, unitCost: 450, lastUpdated: "27 พ.ค. 2569 07:50 น." },
  { id: "MAT-011", name: "ดินปลูก", category: "เมล็ดพันธุ์และต้นพันธุ์", unit: "ตัน", minimumStock: 2, unitCost: 950, lastUpdated: "26 พ.ค. 2569 12:15 น." },
  { id: "MAT-012", name: "น้ำมันเบนซิน", category: "เชื้อเพลิงและพลังงาน", unit: "ลิตร", minimumStock: 30, unitCost: 42, lastUpdated: "27 พ.ค. 2569 08:45 น." },
  { id: "MAT-013", name: "น้ำมันดีเซล", category: "เชื้อเพลิงและพลังงาน", unit: "ลิตร", minimumStock: 80, unitCost: 36, lastUpdated: "27 พ.ค. 2569 08:45 น." },
  { id: "MAT-014", name: "ฟางคลุมดิน", category: "วัสดุคลุมดินและก่อสร้าง", unit: "ก้อน", minimumStock: 40, unitCost: 35, lastUpdated: "22 พ.ค. 2569 14:10 น." },
  { id: "MAT-015", name: "ไม้ไผ่ค้ำยัน", category: "วัสดุคลุมดินและก่อสร้าง", unit: "ลำ", minimumStock: 60, unitCost: 18, lastUpdated: "25 พ.ค. 2569 10:05 น." },
  { id: "MAT-016", name: "ก้อนหินจัดขอบแปลง", category: "วัสดุคลุมดินและก่อสร้าง", unit: "ก้อน", minimumStock: 100, unitCost: 12, lastUpdated: "21 พ.ค. 2569 09:00 น." },
  { id: "MAT-017", name: "กระสอบ", category: "วัสดุคลุมดินและก่อสร้าง", unit: "ใบ", minimumStock: 120, unitCost: 9, lastUpdated: "20 พ.ค. 2569 16:10 น." },
  { id: "MAT-018", name: "ถุงเพาะชำ", category: "ภาชนะและวัสดุจัดเก็บ", unit: "ใบ", minimumStock: 500, unitCost: 1.8, lastUpdated: "27 พ.ค. 2569 11:25 น." },
  { id: "MAT-019", name: "กระถางดำ", category: "ภาชนะและวัสดุจัดเก็บ", unit: "ใบ", minimumStock: 160, unitCost: 16, lastUpdated: "26 พ.ค. 2569 13:00 น." },
  { id: "MAT-020", name: "เข่งพลาสติก", category: "ภาชนะและวัสดุจัดเก็บ", unit: "ใบ", minimumStock: 80, unitCost: 75, lastUpdated: "25 พ.ค. 2569 15:45 น." },
];

const initialInventoryImports = [
  { id: "IMP-001", materialId: "MAT-001", quantity: 500, unitPrice: 24, supplier: "ร้านเกษตรลพบุรี", billNo: "GS-INV-0527-01", importDate: "2026-05-27", receiver: "คุณหวาน", note: "รับเข้าตามแผนเดือนพฤษภาคม" },
  { id: "IMP-002", materialId: "MAT-002", quantity: 180, unitPrice: 55, supplier: "Good Bio Supply", billNo: "GS-INV-0527-02", importDate: "2026-05-27", receiver: "พี่สมชาย", note: "ตรวจกลิ่นและสีแล้วปกติ" },
  { id: "IMP-003", materialId: "MAT-006", quantity: 120, unitPrice: 95, supplier: "โรงเผาไบโอชา", billNo: "GS-INV-0527-03", importDate: "2026-05-27", receiver: "คุณหวาน", note: "สำหรับงานพ่นป้องกันแมลง" },
  { id: "IMP-004", materialId: "MAT-010", quantity: 30, unitPrice: 450, supplier: "Nursery Partner", billNo: "GS-INV-0526-01", importDate: "2026-05-26", receiver: "พี่ไกร", note: "กล้าไม้แข็งแรง" },
  { id: "IMP-005", materialId: "MAT-013", quantity: 180, unitPrice: 36, supplier: "ปั๊มน้ำมันโคกเจริญ", billNo: "GS-FUEL-0527", importDate: "2026-05-27", receiver: "พี่สมชาย", note: "เติมถังสำรองรถไถ" },
  { id: "IMP-006", materialId: "MAT-018", quantity: 1200, unitPrice: 1.8, supplier: "ร้านถุงเพาะชำ", billNo: "GS-POT-0526", importDate: "2026-05-26", receiver: "คุณหวาน", note: "ถุงไซซ์กลาง" },
  { id: "IMP-007", materialId: "MAT-014", quantity: 120, unitPrice: 35, supplier: "เกษตรกรในพื้นที่", billNo: "GS-STRAW-0524", importDate: "2026-05-24", receiver: "พี่ไกร", note: "ใช้คลุมดินรอบโครงข่ายน้ำ" },
  { id: "IMP-008", materialId: "MAT-007", quantity: 420, unitPrice: 18, supplier: "GoodSeed Biochar", billNo: "GS-BIO-0525", importDate: "2026-05-25", receiver: "คุณหวาน", note: "ผลิตภายในฟาร์ม" },
  { id: "IMP-009", materialId: "MAT-011", quantity: 6, unitPrice: 950, supplier: "ดินปลูกชุมชน", billNo: "GS-SOIL-0526", importDate: "2026-05-26", receiver: "พี่ไกร", note: "ตรวจความชื้นแล้ว" },
  { id: "IMP-010", materialId: "MAT-020", quantity: 140, unitPrice: 75, supplier: "ร้านวัสดุจัดสวน", billNo: "GS-BASKET-0525", importDate: "2026-05-25", receiver: "พี่สมชาย", note: "สำหรับไม้ล้อมขนาดกลาง" },
];

const initialInventoryWithdrawals = [
  { id: "WDR-001", materialId: "MAT-001", quantity: 210, usageType: "ใส่ปุ๋ยรอบโคนต้น", plot: "แปลง A1-A10", requester: "พี่ไกร", approvedBy: "คุณหวาน", withdrawDate: "2026-05-27", note: "งานเช้า" },
  { id: "WDR-002", materialId: "MAT-002", quantity: 70, usageType: "บำรุงต้นไม้ผิดปกติ", plot: "แปลง B1", requester: "พี่สมชาย", approvedBy: "คุณหวาน", withdrawDate: "2026-05-27", note: "ผสมตามอัตรา 1:500" },
  { id: "WDR-003", materialId: "MAT-006", quantity: 55, usageType: "พ่นป้องกันแมลง", plot: "แปลง A2", requester: "พี่ไกร", approvedBy: "คุณหวาน", withdrawDate: "2026-05-27", note: "รอลมนิ่งก่อนพ่น" },
  { id: "WDR-004", materialId: "MAT-013", quantity: 125, usageType: "ใช้รถไถและปั๊มน้ำ", plot: "Zone 6-7", requester: "พี่สมชาย", approvedBy: "Admin Farm", withdrawDate: "2026-05-27", note: "เติมรถและถังสำรอง" },
  { id: "WDR-005", materialId: "MAT-018", quantity: 680, usageType: "เพาะกล้าชุดใหม่", plot: "โรงเพาะชำ", requester: "พี่ไกร", approvedBy: "คุณหวาน", withdrawDate: "2026-05-26", note: "ใช้กับกล้าจามจุรีทอง" },
  { id: "WDR-006", materialId: "MAT-014", quantity: 95, usageType: "คลุมดินกันความชื้น", plot: "รอบโครงข่ายกระจายน้ำ", requester: "พี่สมชาย", approvedBy: "คุณหวาน", withdrawDate: "2026-05-25", note: "คลุมพื้นที่ทดลอง" },
  { id: "WDR-007", materialId: "MAT-007", quantity: 310, usageType: "ปรับปรุงดิน", plot: "แปลงทดลอง B1", requester: "คุณหวาน", approvedBy: "Owner", withdrawDate: "2026-05-26", note: "สูตรทดลอง GS-03" },
  { id: "WDR-008", materialId: "MAT-011", quantity: 4.5, usageType: "ผสมวัสดุปลูก", plot: "โรงเพาะชำ", requester: "พี่ไกร", approvedBy: "คุณหวาน", withdrawDate: "2026-05-27", note: "ใช้กับถาดเพาะใหม่" },
  { id: "WDR-009", materialId: "MAT-020", quantity: 75, usageType: "จัดเก็บไม้ล้อม", plot: "แปลง A", requester: "พี่สมชาย", approvedBy: "คุณหวาน", withdrawDate: "2026-05-24", note: "เข่งสำหรับต้นขนาดกลาง" },
];

const initialEquipmentInventory = [
  { id: "EQ-001", equipmentName: "เครื่องตัดหญ้า Honda", category: "เครื่องมือและอุปกรณ์", totalQuantity: 4, workingQuantity: 3, damagedQuantity: 1, currentHolder: "พี่ไกร", maintenanceStatus: "รอซ่อม", maintenanceDate: "21 พ.ค. 2569", note: "ใบมีดชุดที่ 2 สั่นผิดปกติ" },
  { id: "EQ-002", equipmentName: "เครื่องพ่นยาแบตเตอรี่", category: "เครื่องมือและอุปกรณ์", totalQuantity: 6, workingQuantity: 6, damagedQuantity: 0, currentHolder: "พี่สมชาย", maintenanceStatus: "พร้อมใช้งาน", maintenanceDate: "26 พ.ค. 2569", note: "ชาร์จเต็มทุกเครื่อง" },
  { id: "EQ-003", equipmentName: "ปั๊มน้ำ 2 นิ้ว", category: "เครื่องมือและอุปกรณ์", totalQuantity: 3, workingQuantity: 2, damagedQuantity: 1, currentHolder: "ทีมระบบน้ำ", maintenanceStatus: "ตรวจเช็ค", maintenanceDate: "24 พ.ค. 2569", note: "แรงดันตกในรอบบ่าย" },
  { id: "EQ-004", equipmentName: "สายยาง / สปริงเกอร์", category: "เครื่องมือและอุปกรณ์", totalQuantity: 40, workingQuantity: 38, damagedQuantity: 2, currentHolder: "ทีมแปลง A", maintenanceStatus: "กำลังใช้งาน", maintenanceDate: "25 พ.ค. 2569", note: "เปลี่ยนหัวสปริงเกอร์ Zone 2" },
  { id: "EQ-005", equipmentName: "รถเข็นวัสดุ", category: "เครื่องมือและอุปกรณ์", totalQuantity: 8, workingQuantity: 8, damagedQuantity: 0, currentHolder: "คลังวัสดุ", maintenanceStatus: "พร้อมใช้งาน", maintenanceDate: "20 พ.ค. 2569", note: "พร้อมใช้งานทั้งหมด" },
  { id: "EQ-006", equipmentName: "เครื่องมือช่างประจำแปลง", category: "เครื่องมือและอุปกรณ์", totalQuantity: 12, workingQuantity: 11, damagedQuantity: 1, currentHolder: "พี่สมชาย", maintenanceStatus: "ซ่อมบำรุงแล้ว", maintenanceDate: "27 พ.ค. 2569", note: "เปลี่ยนด้ามจอบ 1 ชุด" },
];

function buildInventoryStockRows(imports, withdrawals) {
  return inventoryMaterials.map((material) => {
    const totalImported = imports.filter((item) => item.materialId === material.id).reduce((sum, item) => sum + Number(item.quantity || 0), 0);
    const totalWithdrawn = withdrawals.filter((item) => item.materialId === material.id).reduce((sum, item) => sum + Number(item.quantity || 0), 0);
    const remaining = Math.max(0, totalImported - totalWithdrawn);
    const status = remaining <= material.minimumStock ? "ต้องสั่งเพิ่ม" : remaining <= material.minimumStock * 1.5 ? "ใกล้หมด" : "ปกติ";
    return { ...material, totalImported, totalWithdrawn, remaining, status, stockValue: remaining * material.unitCost };
  });
}

function LegacyInventoryWarehousePage() {
  const [importRecords, setImportRecords] = useState(initialInventoryImports);
  const [withdrawRecords, setWithdrawRecords] = useState(initialInventoryWithdrawals);
  const [equipmentRows, setEquipmentRows] = useState(initialEquipmentInventory);
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("ทั้งหมด");
  const [historyFilter, setHistoryFilter] = useState({ date: "", category: "ทั้งหมด", keyword: "", plot: "", staff: "" });
  const [notice, setNotice] = useState("");
  const [importForm, setImportForm] = useState({
    importDate: "2026-05-27",
    category: inventoryMaterials[0].category,
    materialId: inventoryMaterials[0].id,
    quantity: 50,
    unitPrice: inventoryMaterials[0].unitCost,
    supplier: "ร้านเกษตรลพบุรี",
    billNo: "GS-INV-NEW",
    receiver: "คุณหวาน",
    note: "",
  });
  const [withdrawForm, setWithdrawForm] = useState({
    withdrawDate: "2026-05-27",
    category: inventoryMaterials[0].category,
    materialId: inventoryMaterials[0].id,
    quantity: 20,
    plot: "แปลง A1",
    usageType: "งานบำรุงต้นไม้",
    requester: "พี่ไกร",
    approvedBy: "คุณหวาน",
    note: "",
  });

  const stockRows = useMemo(() => buildInventoryStockRows(importRecords, withdrawRecords), [importRecords, withdrawRecords]);
  const today = "2026-05-27";
  const todayImports = importRecords.filter((item) => item.importDate === today);
  const todayWithdraws = withdrawRecords.filter((item) => item.withdrawDate === today);
  const lowStockRows = stockRows.filter((item) => item.status !== "ปกติ");
  const damagedEquipment = equipmentRows.reduce((sum, item) => sum + item.damagedQuantity, 0);
  const totalStockValue = stockRows.reduce((sum, item) => sum + item.stockValue, 0);
  const materialOptions = inventoryMaterials.filter((item) => item.category === importForm.category);
  const withdrawMaterialOptions = inventoryMaterials.filter((item) => item.category === withdrawForm.category);
  const filteredStockRows = stockRows.filter((item) => {
    const keywordMatch = item.name.includes(searchTerm) || item.category.includes(searchTerm);
    const categoryMatch = categoryFilter === "ทั้งหมด" || item.category === categoryFilter;
    return keywordMatch && categoryMatch;
  });
  const historyRows = useMemo(() => {
    const imports = importRecords.map((item) => {
      const material = inventoryMaterials.find((entry) => entry.id === item.materialId);
      return { ...item, type: "นำเข้า", date: item.importDate, materialName: material?.name || "-", category: material?.category || "-", quantityText: `${item.quantity} ${material?.unit || ""}`, staff: item.receiver, plot: "-", amount: Number(item.quantity || 0) * Number(item.unitPrice || 0) };
    });
    const withdrawals = withdrawRecords.map((item) => {
      const material = inventoryMaterials.find((entry) => entry.id === item.materialId);
      return { ...item, type: "เบิกใช้", date: item.withdrawDate, materialName: material?.name || "-", category: material?.category || "-", quantityText: `${item.quantity} ${material?.unit || ""}`, staff: item.requester, plot: item.plot, amount: 0 };
    });
    return [...imports, ...withdrawals].sort((a, b) => b.date.localeCompare(a.date));
  }, [importRecords, withdrawRecords]);
  const filteredHistoryRows = historyRows.filter((item) => {
    const keyword = historyFilter.keyword.trim();
    return (!historyFilter.date || item.date === historyFilter.date)
      && (historyFilter.category === "ทั้งหมด" || item.category === historyFilter.category)
      && (!keyword || item.materialName.includes(keyword) || item.type.includes(keyword))
      && (!historyFilter.plot || item.plot.includes(historyFilter.plot))
      && (!historyFilter.staff || item.staff.includes(historyFilter.staff));
  });

  const categories = ["ทั้งหมด", ...inventoryCategoryGroups.map((item) => item.name)];
  const inputClass = "mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-3 py-3 text-sm font-semibold text-goodseed-900 outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100";
  const compactInputClass = "w-full rounded-xl border border-goodseed-100 bg-white px-3 py-2.5 text-sm font-semibold text-goodseed-900 outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100";
  const selectedImportMaterial = inventoryMaterials.find((item) => item.id === importForm.materialId) || inventoryMaterials[0];
  const selectedWithdrawMaterial = inventoryMaterials.find((item) => item.id === withdrawForm.materialId) || inventoryMaterials[0];
  const importTotal = Number(importForm.quantity || 0) * Number(importForm.unitPrice || 0);

  const addImportRecord = (event) => {
    event.preventDefault();
    const material = inventoryMaterials.find((item) => item.id === importForm.materialId);
    setImportRecords((records) => [
      {
        id: `IMP-${Date.now()}`,
        materialId: importForm.materialId,
        quantity: Number(importForm.quantity || 0),
        unitPrice: Number(importForm.unitPrice || material?.unitCost || 0),
        supplier: importForm.supplier,
        billNo: importForm.billNo,
        importDate: importForm.importDate,
        receiver: importForm.receiver,
        note: importForm.note || "บันทึกจากฟอร์มนำเข้า",
      },
      ...records,
    ]);
    setNotice(`บันทึกนำเข้า ${material?.name || "วัสดุ"} แล้ว และคำนวณคงเหลือใหม่ทันที`);
  };

  const addWithdrawRecord = (event) => {
    event.preventDefault();
    const material = inventoryMaterials.find((item) => item.id === withdrawForm.materialId);
    setWithdrawRecords((records) => [
      {
        id: `WDR-${Date.now()}`,
        materialId: withdrawForm.materialId,
        quantity: Number(withdrawForm.quantity || 0),
        usageType: withdrawForm.usageType,
        plot: withdrawForm.plot,
        requester: withdrawForm.requester,
        approvedBy: withdrawForm.approvedBy,
        withdrawDate: withdrawForm.withdrawDate,
        note: withdrawForm.note || "บันทึกจากฟอร์มเบิกใช้",
      },
      ...records,
    ]);
    setNotice(`บันทึกเบิกใช้ ${material?.name || "วัสดุ"} แล้ว และ Dashboard อัปเดตแบบ Real-time`);
  };

  const addEquipmentRecord = () => {
    setEquipmentRows((rows) => [
      {
        id: `EQ-${Date.now()}`,
        equipmentName: "ชุดเครื่องมือช่างใหม่",
        category: "เครื่องมือและอุปกรณ์",
        totalQuantity: 1,
        workingQuantity: 1,
        damagedQuantity: 0,
        currentHolder: "คลังวัสดุ",
        maintenanceStatus: "พร้อมใช้งาน",
        maintenanceDate: "27 พ.ค. 2569",
        note: "เพิ่มจากปุ่ม Add Equipment",
      },
      ...rows,
    ]);
    setNotice("เพิ่มอุปกรณ์ใหม่แล้ว");
  };

  const exportStockCsv = () => {
    const header = "ชื่อวัสดุ,หมวดหมู่,หน่วย,นำเข้า,เบิกใช้,คงเหลือ,Minimum Stock,Status,อัปเดตล่าสุด\n";
    const rows = stockRows.map((item) => [item.name, item.category, item.unit, item.totalImported, item.totalWithdrawn, item.remaining, item.minimumStock, item.status, item.lastUpdated].join(",")).join("\n");
    downloadFile("goodseed-inventory-stock.csv", header + rows, "text/csv;charset=utf-8");
  };

  return (
    <section className="space-y-6">
      <SectionHeader
        title="Inventory / Warehouse"
        subtitle="ระบบคลังวัสดุสำหรับบันทึกนำเข้า เบิกใช้ ตรวจสอบคงเหลือ ติดตามอุปกรณ์ เครื่องมือ และแจ้งเตือนสต๊อกแบบ Real-time"
        action={
          <div className="flex flex-wrap gap-2">
            <a href="#inventory-import-form" className="inline-flex min-h-10 items-center gap-2 rounded-xl bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white shadow-soft hover:bg-goodseed-800"><Icon name="upload" className="h-4 w-4" />Add Import</a>
            <a href="#inventory-withdraw-form" className="inline-flex min-h-10 items-center gap-2 rounded-xl border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="box" className="h-4 w-4" />Add Withdraw</a>
            <button onClick={addEquipmentRecord} className="inline-flex min-h-10 items-center gap-2 rounded-xl border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="wrench" className="h-4 w-4" />Add Equipment</button>
          </div>
        }
      />

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-6">
        {[
          ["จำนวนวัสดุทั้งหมด", stockRows.length, "รายการ", "box", "bg-goodseed-100 text-goodseed-800"],
          ["วัสดุนำเข้าวันนี้", todayImports.length, "รายการ", "upload", "bg-emerald-100 text-emerald-800"],
          ["วัสดุเบิกใช้วันนี้", todayWithdraws.length, "รายการ", "download", "bg-sky-100 text-sky-800"],
          ["รายการใกล้หมด", lowStockRows.length, "รายการ", "bell", "bg-amber-100 text-amber-800"],
          ["มูลค่าสต๊อกรวม", totalStockValue.toLocaleString("th-TH"), "บาท", "money", "bg-goodseed-50 text-goodseed-900"],
          ["อุปกรณ์ชำรุด", damagedEquipment, "รายการ", "wrench", "bg-red-100 text-red-700"],
        ].map(([label, value, unit, icon, tone]) => <DashboardCard key={label} label={label} value={value} unit={unit} icon={icon} tone={tone} />)}
      </div>

      {notice && <div className="rounded-xl border border-goodseed-100 bg-goodseed-50 px-4 py-3 text-sm font-extrabold text-goodseed-800 shadow-soft">{notice}</div>}

      <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
        <main className="min-w-0 space-y-6">
          <DashboardPanel title="Search Materials & Smart Actions" action={<Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Auto Remaining Calculation</Badge>}>
            <div className="grid gap-3 lg:grid-cols-[1fr_260px_auto]">
              <label className="text-sm font-extrabold text-goodseed-900">
                Search Materials
                <input value={searchTerm} onChange={(event) => setSearchTerm(event.target.value)} className={inputClass} placeholder="ค้นหาวัสดุ หมวดหมู่ หรือรายการ" />
              </label>
              <label className="text-sm font-extrabold text-goodseed-900">
                Filter by Category
                <select value={categoryFilter} onChange={(event) => setCategoryFilter(event.target.value)} className={inputClass}>
                  {categories.map((item) => <option key={item}>{item}</option>)}
                </select>
              </label>
              <div className="flex flex-wrap items-end gap-2">
                <button className="inline-flex min-h-11 items-center gap-2 rounded-xl border border-goodseed-200 px-4 py-2 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="qr" className="h-4 w-4" />QR Code</button>
                <button className="inline-flex min-h-11 items-center gap-2 rounded-xl border border-goodseed-200 px-4 py-2 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="camera" className="h-4 w-4" />Barcode Scan</button>
              </div>
            </div>
          </DashboardPanel>

          <div className="grid gap-6 lg:grid-cols-2">
            <DashboardPanel id="inventory-import-form" title="Import Materials Form / ฟอร์มนำเข้าวัสดุ">
              <form onSubmit={addImportRecord} className="grid gap-3">
                <div className="grid gap-3 sm:grid-cols-2">
                  <label className="text-sm font-extrabold text-goodseed-900">วันที่นำเข้า<input type="date" value={importForm.importDate} onChange={(event) => setImportForm({ ...importForm, importDate: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">หมวดหมู่<select value={importForm.category} onChange={(event) => {
                    const firstMaterial = inventoryMaterials.find((item) => item.category === event.target.value) || inventoryMaterials[0];
                    setImportForm({ ...importForm, category: event.target.value, materialId: firstMaterial.id, unitPrice: firstMaterial.unitCost });
                  }} className={inputClass}>{inventoryCategoryGroups.slice(0, 5).map((item) => <option key={item.name}>{item.name}</option>)}</select></label>
                  <label className="text-sm font-extrabold text-goodseed-900">รายการวัสดุ<select value={importForm.materialId} onChange={(event) => {
                    const material = inventoryMaterials.find((item) => item.id === event.target.value);
                    setImportForm({ ...importForm, materialId: event.target.value, unitPrice: material?.unitCost || importForm.unitPrice });
                  }} className={inputClass}>{materialOptions.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
                  <label className="text-sm font-extrabold text-goodseed-900">จำนวน<input type="number" min="0" step="0.1" value={importForm.quantity} onChange={(event) => setImportForm({ ...importForm, quantity: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">หน่วย<input value={selectedImportMaterial.unit} readOnly className={`${inputClass} bg-goodseed-50`} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">ราคา/หน่วย<input type="number" min="0" step="0.1" value={importForm.unitPrice} onChange={(event) => setImportForm({ ...importForm, unitPrice: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">ราคารวม<input value={`${importTotal.toLocaleString("th-TH")} บาท`} readOnly className={`${inputClass} bg-goodseed-50`} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">Supplier<input value={importForm.supplier} onChange={(event) => setImportForm({ ...importForm, supplier: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">เลขบิล<input value={importForm.billNo} onChange={(event) => setImportForm({ ...importForm, billNo: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">ผู้ตรวจรับ<input value={importForm.receiver} onChange={(event) => setImportForm({ ...importForm, receiver: event.target.value })} className={inputClass} /></label>
                </div>
                <label className="text-sm font-extrabold text-goodseed-900">รูปภาพบิลหรือสินค้า<input type="file" accept="image/*,.pdf" className={inputClass} /></label>
                <label className="text-sm font-extrabold text-goodseed-900">หมายเหตุ<textarea value={importForm.note} onChange={(event) => setImportForm({ ...importForm, note: event.target.value })} className={inputClass} rows="3" /></label>
                <button type="submit" className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-soft hover:bg-goodseed-800"><Icon name="upload" className="h-4 w-4" />บันทึกนำเข้าวัสดุ</button>
              </form>
            </DashboardPanel>

            <DashboardPanel id="inventory-withdraw-form" title="Withdraw Materials Form / ฟอร์มเบิกใช้งาน">
              <form onSubmit={addWithdrawRecord} className="grid gap-3">
                <div className="grid gap-3 sm:grid-cols-2">
                  <label className="text-sm font-extrabold text-goodseed-900">วันที่เบิกใช้<input type="date" value={withdrawForm.withdrawDate} onChange={(event) => setWithdrawForm({ ...withdrawForm, withdrawDate: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">หมวดหมู่<select value={withdrawForm.category} onChange={(event) => {
                    const firstMaterial = inventoryMaterials.find((item) => item.category === event.target.value) || inventoryMaterials[0];
                    setWithdrawForm({ ...withdrawForm, category: event.target.value, materialId: firstMaterial.id });
                  }} className={inputClass}>{inventoryCategoryGroups.slice(0, 5).map((item) => <option key={item.name}>{item.name}</option>)}</select></label>
                  <label className="text-sm font-extrabold text-goodseed-900">รายการวัสดุ<select value={withdrawForm.materialId} onChange={(event) => setWithdrawForm({ ...withdrawForm, materialId: event.target.value })} className={inputClass}>{withdrawMaterialOptions.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
                  <label className="text-sm font-extrabold text-goodseed-900">จำนวนที่เบิก<input type="number" min="0" step="0.1" value={withdrawForm.quantity} onChange={(event) => setWithdrawForm({ ...withdrawForm, quantity: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">หน่วย<input value={selectedWithdrawMaterial.unit} readOnly className={`${inputClass} bg-goodseed-50`} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">ใช้ในแปลง/โซน<input value={withdrawForm.plot} onChange={(event) => setWithdrawForm({ ...withdrawForm, plot: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">ใช้สำหรับงานอะไร<input value={withdrawForm.usageType} onChange={(event) => setWithdrawForm({ ...withdrawForm, usageType: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">ผู้เบิก<input value={withdrawForm.requester} onChange={(event) => setWithdrawForm({ ...withdrawForm, requester: event.target.value })} className={inputClass} /></label>
                  <label className="text-sm font-extrabold text-goodseed-900">ผู้อนุมัติ<input value={withdrawForm.approvedBy} onChange={(event) => setWithdrawForm({ ...withdrawForm, approvedBy: event.target.value })} className={inputClass} /></label>
                </div>
                <label className="text-sm font-extrabold text-goodseed-900">รูปภาพประกอบ<input type="file" accept="image/*" capture="environment" className={inputClass} /></label>
                <label className="text-sm font-extrabold text-goodseed-900">หมายเหตุ<textarea value={withdrawForm.note} onChange={(event) => setWithdrawForm({ ...withdrawForm, note: event.target.value })} className={inputClass} rows="3" /></label>
                <button type="submit" className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white shadow-soft hover:bg-goodseed-800"><Icon name="download" className="h-4 w-4" />บันทึกเบิกใช้งาน</button>
              </form>
            </DashboardPanel>
          </div>

          <DashboardPanel id="current-stock" title="Current Stock Table / ตารางสต๊อกคงเหลือ" action={<Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">คงเหลือ = นำเข้า - เบิกใช้</Badge>}>
            <div className="hidden overflow-x-auto lg:block">
              <table className="min-w-[980px] w-full text-left text-sm">
                <thead className="bg-goodseed-50 text-goodseed-800">
                  <tr>{["ชื่อวัสดุ", "หมวดหมู่", "หน่วย", "นำเข้าทั้งหมด", "เบิกใช้ทั้งหมด", "คงเหลือ", "Minimum Stock", "Status", "อัปเดตล่าสุด"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr>
                </thead>
                <tbody className="divide-y divide-goodseed-100">
                  {filteredStockRows.map((item) => (
                    <tr key={item.id} className="hover:bg-goodseed-50/60">
                      <td className="px-3 py-3 font-extrabold text-goodseed-950">{item.name}</td>
                      <td className="px-3 py-3 font-semibold text-goodseed-700">{item.category}</td>
                      <td className="px-3 py-3 font-semibold text-slate-700">{item.unit}</td>
                      <td className="px-3 py-3 font-bold text-slate-800">{item.totalImported.toLocaleString("th-TH")}</td>
                      <td className="px-3 py-3 font-bold text-slate-800">{item.totalWithdrawn.toLocaleString("th-TH")}</td>
                      <td className="px-3 py-3 text-lg font-black text-goodseed-900">{item.remaining.toLocaleString("th-TH")}</td>
                      <td className="px-3 py-3 font-bold text-slate-700">{item.minimumStock.toLocaleString("th-TH")}</td>
                      <td className="px-3 py-3"><StatusBadge status={item.status} /></td>
                      <td className="px-3 py-3 text-xs font-semibold text-slate-600">{item.lastUpdated}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="grid gap-3 lg:hidden">
              {filteredStockRows.map((item) => (
                <article key={item.id} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <h4 className="text-base font-extrabold text-goodseed-950">{item.name}</h4>
                      <p className="mt-1 text-xs font-bold text-goodseed-600">{item.category}</p>
                    </div>
                    <StatusBadge status={item.status} />
                  </div>
                  <div className="mt-4 grid grid-cols-2 gap-2 text-sm">
                    <MiniMetric label="นำเข้า" value={`${item.totalImported.toLocaleString("th-TH")} ${item.unit}`} />
                    <MiniMetric label="เบิกใช้" value={`${item.totalWithdrawn.toLocaleString("th-TH")} ${item.unit}`} />
                    <MiniMetric label="คงเหลือ" value={`${item.remaining.toLocaleString("th-TH")} ${item.unit}`} />
                    <MiniMetric label="Minimum" value={`${item.minimumStock.toLocaleString("th-TH")} ${item.unit}`} danger={item.status === "ต้องสั่งเพิ่ม"} />
                  </div>
                </article>
              ))}
            </div>
          </DashboardPanel>

          <DashboardPanel id="equipment-tools" title="Equipment & Tools Table / ตารางอุปกรณ์และเครื่องมือ" action={<Badge className="bg-sky-100 text-sky-800 ring-sky-200">ติดตามสถานะ ไม่คำนวณคงเหลือ</Badge>}>
            <div className="hidden overflow-x-auto lg:block">
              <table className="min-w-[920px] w-full text-left text-sm">
                <thead className="bg-goodseed-50 text-goodseed-800">
                  <tr>{["ชื่ออุปกรณ์", "หมวดหมู่", "จำนวนทั้งหมด", "ใช้งานได้", "ชำรุด", "ผู้ถือครอง", "สถานะซ่อมบำรุง", "วันที่ซ่อมล่าสุด", "หมายเหตุ"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr>
                </thead>
                <tbody className="divide-y divide-goodseed-100">
                  {equipmentRows.map((item) => (
                    <tr key={item.id} className="hover:bg-goodseed-50/60">
                      <td className="px-3 py-3 font-extrabold text-goodseed-950">{item.equipmentName}</td>
                      <td className="px-3 py-3 font-semibold text-goodseed-700">{item.category}</td>
                      <td className="px-3 py-3 font-bold">{item.totalQuantity}</td>
                      <td className="px-3 py-3 font-bold text-goodseed-800">{item.workingQuantity}</td>
                      <td className="px-3 py-3 font-bold text-red-700">{item.damagedQuantity}</td>
                      <td className="px-3 py-3 font-semibold">{item.currentHolder}</td>
                      <td className="px-3 py-3"><StatusBadge status={item.maintenanceStatus} /></td>
                      <td className="px-3 py-3 text-xs font-semibold text-slate-600">{item.maintenanceDate}</td>
                      <td className="px-3 py-3 text-xs font-semibold text-slate-600">{item.note}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="grid gap-3 md:grid-cols-2 lg:hidden">
              {equipmentRows.map((item) => (
                <article key={item.id} className="rounded-xl border border-goodseed-100 bg-white p-4 shadow-sm">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <h4 className="font-extrabold text-goodseed-950">{item.equipmentName}</h4>
                      <p className="mt-1 text-xs font-bold text-goodseed-600">{item.currentHolder}</p>
                    </div>
                    <StatusBadge status={item.maintenanceStatus} />
                  </div>
                  <div className="mt-4 grid grid-cols-3 gap-2 text-center text-xs font-bold">
                    <span className="rounded-lg bg-goodseed-50 p-2">ทั้งหมด<br />{item.totalQuantity}</span>
                    <span className="rounded-lg bg-goodseed-50 p-2 text-goodseed-800">ใช้งานได้<br />{item.workingQuantity}</span>
                    <span className="rounded-lg bg-red-50 p-2 text-red-700">ชำรุด<br />{item.damagedQuantity}</span>
                  </div>
                  <p className="mt-3 text-sm font-semibold leading-6 text-slate-600">{item.note}</p>
                </article>
              ))}
            </div>
          </DashboardPanel>

          <DashboardPanel id="transaction-history" title="Transaction History / ประวัตินำเข้าและเบิกใช้" action={<a href="#transaction-history" className="text-sm font-extrabold text-goodseed-700">View History</a>}>
            <div className="mb-4 grid gap-3 md:grid-cols-5">
              <input type="date" value={historyFilter.date} onChange={(event) => setHistoryFilter({ ...historyFilter, date: event.target.value })} className={compactInputClass} />
              <select value={historyFilter.category} onChange={(event) => setHistoryFilter({ ...historyFilter, category: event.target.value })} className={compactInputClass}>{categories.map((item) => <option key={item}>{item}</option>)}</select>
              <input value={historyFilter.keyword} onChange={(event) => setHistoryFilter({ ...historyFilter, keyword: event.target.value })} className={compactInputClass} placeholder="รายการวัสดุ" />
              <input value={historyFilter.plot} onChange={(event) => setHistoryFilter({ ...historyFilter, plot: event.target.value })} className={compactInputClass} placeholder="แปลง/โซน" />
              <input value={historyFilter.staff} onChange={(event) => setHistoryFilter({ ...historyFilter, staff: event.target.value })} className={compactInputClass} placeholder="ชื่อพนักงาน" />
            </div>
            <div className="space-y-3">
              {filteredHistoryRows.slice(0, 8).map((item) => (
                <div key={`${item.type}-${item.id}`} className="grid gap-3 rounded-xl border border-goodseed-100 bg-white p-4 text-sm shadow-sm md:grid-cols-[100px_1fr_140px_120px_120px] md:items-center">
                  <Badge className={item.type === "นำเข้า" ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : "bg-sky-100 text-sky-800 ring-sky-200"}>{item.type}</Badge>
                  <div>
                    <p className="font-extrabold text-goodseed-950">{item.materialName}</p>
                    <p className="mt-1 text-xs font-semibold text-slate-600">{item.category} / {item.plot}</p>
                  </div>
                  <p className="font-bold text-slate-700">{item.quantityText}</p>
                  <p className="font-bold text-slate-700">{item.staff}</p>
                  <p className="text-xs font-bold text-slate-500">{item.date}</p>
                </div>
              ))}
            </div>
          </DashboardPanel>

          <div className="grid gap-6 lg:grid-cols-2">
            <DashboardPanel title="Reports / Export Center" action={<button onClick={exportStockCsv} className="inline-flex items-center gap-2 rounded-xl bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white"><Icon name="download" className="h-4 w-4" />Export CSV</button>}>
              <div className="grid gap-3 sm:grid-cols-2">
                {["รายงานรายวัน", "รายงานรายสัปดาห์", "รายงานรายเดือน", "รายงานสต๊อกคงเหลือ", "ประวัติการนำเข้า/เบิกใช้", "รายงานซ่อมบำรุงอุปกรณ์"].map((item) => (
                  <div key={item} className="rounded-xl border border-goodseed-100 bg-goodseed-50 p-4">
                    <p className="font-extrabold text-goodseed-950">{item}</p>
                    <div className="mt-3 flex flex-wrap gap-2">
                      {["PDF", "Excel", "CSV"].map((type) => <button key={type} className="rounded-lg bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-100">{type}</button>)}
                    </div>
                  </div>
                ))}
              </div>
            </DashboardPanel>
            <DashboardPanel title="Database Structure">
              <div className="space-y-3">
                {[
                  ["materials", "id, category, item_name, unit, current_stock, minimum_stock, image, status"],
                  ["imports", "id, material_id, quantity, unit_price, total_price, supplier, import_date, receiver"],
                  ["withdrawals", "id, material_id, quantity, usage_type, plot, requester, approved_by, withdraw_date"],
                  ["equipments", "id, equipment_name, category, total_quantity, working_quantity, damaged_quantity, current_holder, maintenance_date"],
                ].map(([table, fields]) => <div key={table} className="rounded-xl bg-goodseed-50 p-4"><p className="font-black text-goodseed-950">{table}</p><p className="mt-2 text-xs font-semibold leading-6 text-goodseed-700">{fields}</p></div>)}
              </div>
            </DashboardPanel>
          </div>
        </main>

        <aside className="space-y-6">
          <DashboardPanel title="Alerts / Notifications" action={<Badge className="bg-red-100 text-red-700 ring-red-200">{lowStockRows.length + damagedEquipment} แจ้งเตือน</Badge>}>
            <div className="space-y-3">
              {[...lowStockRows.slice(0, 5).map((item) => ({ title: item.name, detail: `คงเหลือ ${item.remaining.toLocaleString("th-TH")} ${item.unit} / Minimum ${item.minimumStock}`, status: item.status })),
                { title: "น้ำมันดีเซลใกล้หมด", detail: "ตรวจสอบถังสำรองก่อนใช้งานรถไถรอบบ่าย", status: "ใกล้หมด" },
                { title: "เครื่องตัดหญ้าชำรุด", detail: "รอซ่อมใบมีดและตรวจแรงสั่น", status: "ชำรุด" },
                { title: "รายการไม่มีการอัปเดตหลายวัน", detail: "ก้อนหินและกระสอบควรตรวจนับซ้ำ", status: "ยังไม่ได้อัปเดต" },
              ].map((item) => (
                <div key={`${item.title}-${item.detail}`} className="rounded-xl border border-goodseed-100 bg-white p-4 shadow-sm">
                  <div className="flex items-start justify-between gap-3">
                    <p className="font-extrabold text-goodseed-950">{item.title}</p>
                    <StatusBadge status={item.status} />
                  </div>
                  <p className="mt-2 text-sm font-semibold leading-6 text-slate-600">{item.detail}</p>
                </div>
              ))}
            </div>
          </DashboardPanel>

          <DashboardPanel title="Activity Timeline">
            <div className="space-y-4">
              {historyRows.slice(0, 6).map((item) => (
                <div key={`timeline-${item.type}-${item.id}`} className="relative pl-6">
                  <span className="absolute left-0 top-1.5 h-3 w-3 rounded-full bg-goodseed-600 ring-4 ring-goodseed-100" />
                  <p className="text-sm font-extrabold text-goodseed-950">{item.type} {item.materialName}</p>
                  <p className="mt-1 text-xs font-semibold text-slate-600">{item.quantityText} / {item.staff} / {item.date}</p>
                </div>
              ))}
            </div>
          </DashboardPanel>

          <DashboardPanel title="Permission Levels">
            <div className="space-y-3">
              {["Owner: ดูและแก้ไขได้ทั้งหมด", "Admin / Manager: เพิ่ม แก้ไข อนุมัติการเบิกได้", "Staff: เพิ่มข้อมูลได้ แต่ลบไม่ได้", "Viewer: ดูข้อมูลอย่างเดียว"].map((item) => (
                <div key={item} className="rounded-xl bg-goodseed-50 p-3 text-sm font-bold leading-6 text-goodseed-800">{item}</div>
              ))}
            </div>
          </DashboardPanel>

          <StockMaterialsGuide />
        </aside>
      </div>
    </section>
  );
}

const flexibleInventoryCategories = [
  { name: "ปุ๋ย / ธาตุอาหาร", items: ["ปุ๋ยยูเรีย", "ปุ๋ยอินทรีย์", "ปุ๋ยน้ำ", "แคลเซียมโบรอน", "ธาตุอาหารเสริม", "อื่น ๆ ระบุเอง"], defaultUnit: "ถุง", countStock: "ต้องนับสต็อก" },
  { name: "วัสดุปลูก", items: ["ดินปลูก", "แกลบดิบ", "แกลบดำ", "ขุยมะพร้าว", "ไบโอชา", "ฟางคลุมดิน", "อื่น ๆ ระบุเอง"], defaultUnit: "กระสอบ", countStock: "ต้องนับสต็อก" },
  { name: "เมล็ดพันธุ์ / กิ่งพันธุ์", items: ["ถั่วแระญี่ปุ่น", "ถั่วบราซิล", "มันญี่ปุ่น", "หญ้าแฝก", "ต้นกล้าไม้ล้อม", "อื่น ๆ ระบุเอง"], defaultUnit: "กิ่ง", countStock: "ต้องนับสต็อก" },
  { name: "สารชีวภัณฑ์ / สารป้องกันโรคแมลง", items: ["จุลินทรีย์ EM", "ฮอร์โมนพืช", "น้ำส้มควันไม้", "สารจับใบ", "เชื้อราบิวเวอเรีย", "อื่น ๆ ระบุเอง"], defaultUnit: "ลิตร", countStock: "ต้องนับสต็อก" },
  { name: "อุปกรณ์การเกษตร", items: ["จอบ", "เสียม", "คราด", "มีด", "กรรไกรตัดกิ่ง", "เครื่องตัดหญ้า", "สายยาง", "บัวรดน้ำ", "อื่น ๆ ระบุเอง"], defaultUnit: "ชิ้น", countStock: "ไม่ต้องนับสต็อก" },
  { name: "เครื่องมือ / เครื่องจักร", items: ["รถไถ", "รถกระบะ", "เครื่องพ่นยา", "เครื่องเจาะดิน", "ปั๊มน้ำ", "เครื่องสูบน้ำ", "อื่น ๆ ระบุเอง"], defaultUnit: "คัน", countStock: "ไม่ต้องนับสต็อก" },
  { name: "ระบบน้ำ / อะไหล่", items: ["สายน้ำหยด", "ท่อ PE", "ข้อต่อ", "วาล์ว", "หัวน้ำหยด", "เทปพันเกลียว", "อื่น ๆ ระบุเอง"], defaultUnit: "ชิ้น", countStock: "ต้องนับสต็อก" },
  { name: "น้ำมัน / เชื้อเพลิง", items: ["น้ำมันเบนซิน", "น้ำมันดีเซล", "น้ำมันเครื่อง", "จาระบี", "แก๊ส", "อื่น ๆ ระบุเอง"], defaultUnit: "ลิตร", countStock: "ต้องนับสต็อก" },
  { name: "วัสดุก่อสร้าง / งานฟาร์ม", items: ["ไม้ไผ่", "ก้อนหิน", "ปูนซีเมนต์", "ทราย", "ลวด", "เสาปูน", "อื่น ๆ ระบุเอง"], defaultUnit: "ชิ้น", countStock: "ต้องนับสต็อก" },
  { name: "บรรจุภัณฑ์ / ถุง / กระสอบ", items: ["ถุงเพาะชำ", "กระสอบ", "กล่องแพ็กสินค้า", "เทปกาว", "ฟิล์มยืด", "เข่งพลาสติก", "อื่น ๆ ระบุเอง"], defaultUnit: "ใบ", countStock: "ต้องนับสต็อก" },
  { name: "อุปกรณ์สำนักงาน", items: ["สมุดบันทึกงาน", "ปากกา", "แฟ้มเอกสาร", "กระดาษ A4", "หมึกพิมพ์", "อื่น ๆ ระบุเอง"], defaultUnit: "ชิ้น", countStock: "ต้องนับสต็อก" },
  { name: "อื่น ๆ", items: ["อื่น ๆ ระบุเอง"], defaultUnit: "ชิ้น", countStock: "ต้องนับสต็อก" },
];

const flexibleInventoryTransactionTypes = ["นำเข้า", "เบิกใช้", "ปรับยอด", "คืนของ", "เสียหาย", "ย้ายคลัง"];
const flexibleInventoryUnits = ["กิโลกรัม", "ถุง", "กระสอบ", "ลิตร", "ขวด", "ชิ้น", "ม้วน", "เมตร", "ต้น", "กิ่ง", "เข่ง", "คัน", "ชุด", "ใบ"];
const flexibleInventoryStockModes = ["ต้องนับสต็อก", "ไม่ต้องนับสต็อก"];
const flexibleInventoryStatuses = ["ใช้งานได้", "ใกล้หมด", "หมด", "ชำรุด", "สูญหาย", "รอซ่อม", "ยืมใช้งาน", "คืนแล้ว"];

const flexibleInventoryStatusClasses = {
  "ใช้งานได้": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  "ใกล้หมด": "bg-amber-100 text-amber-800 ring-amber-200",
  "หมด": "bg-red-100 text-red-700 ring-red-200",
  "ชำรุด": "bg-red-100 text-red-700 ring-red-200",
  "สูญหาย": "bg-rose-100 text-rose-700 ring-rose-200",
  "รอซ่อม": "bg-amber-100 text-amber-800 ring-amber-200",
  "ยืมใช้งาน": "bg-sky-100 text-sky-700 ring-sky-200",
  "คืนแล้ว": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
};

const flexibleTransactionClasses = {
  "นำเข้า": "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  "เบิกใช้": "bg-orange-100 text-orange-800 ring-orange-200",
  "ปรับยอด": "bg-blue-100 text-blue-700 ring-blue-200",
  "คืนของ": "bg-emerald-100 text-emerald-800 ring-emerald-200",
  "เสียหาย": "bg-red-100 text-red-700 ring-red-200",
  "ย้ายคลัง": "bg-purple-100 text-purple-700 ring-purple-200",
};

const initialFlexibleInventoryTransactions = [
  { id: "INV-FLX-001", recordDate: "2026-05-27", transactionType: "นำเข้า", category: "ปุ๋ย / ธาตุอาหาร", itemName: "ปุ๋ยอินทรีย์", details: "ยี่ห้อ GoodGrow สูตรบำรุงดิน ใช้รอบปลูก A-C", quantity: 80, unit: "กระสอบ", unitPrice: 210, supplier: "ร้านเกษตรลพบุรี", requester: "", usagePurpose: "เตรียมสต็อกบำรุงดิน", plot: "คลังกลาง", warehouse: "คลังวัสดุ 1", recorder: "คุณหวาน", status: "ใช้งานได้", countStock: "ต้องนับสต็อก", minimumStock: 20, receiptFile: "bill-organic-fertilizer.jpg", materialFile: "organic-fertilizer-stock.jpg", note: "ตรวจรับครบตามจำนวน", isNewItem: false },
  { id: "INV-FLX-002", recordDate: "2026-05-27", transactionType: "เบิกใช้", category: "ปุ๋ย / ธาตุอาหาร", itemName: "ปุ๋ยอินทรีย์", details: "ใช้รองก้นหลุมและคลุมโคนต้น", quantity: 24, unit: "กระสอบ", unitPrice: 210, supplier: "", requester: "พี่ไกร", usagePurpose: "ใส่ปุ๋ยรอบโคนต้น", plot: "แปลง A1-A10", warehouse: "คลังวัสดุ 1", recorder: "คุณหวาน", status: "ใช้งานได้", countStock: "ต้องนับสต็อก", minimumStock: 20, receiptFile: "", materialFile: "field-use-a1.jpg", note: "อนุมัติเบิกใช้งานเช้า", isNewItem: false },
  { id: "INV-FLX-003", recordDate: "2026-05-27", transactionType: "นำเข้า", category: "วัสดุปลูก", itemName: "ไบโอชา", details: "ผลิตภายในฟาร์ม ขนาด 10 กก. ใช้ปรับปรุงดิน", quantity: 420, unit: "กิโลกรัม", unitPrice: 18, supplier: "GoodSeed Biochar", requester: "", usagePurpose: "สต็อกปรับปรุงดิน", plot: "โรงผลิต", warehouse: "คลังชีวภัณฑ์", recorder: "Admin Farm", status: "ใช้งานได้", countStock: "ต้องนับสต็อก", minimumStock: 150, receiptFile: "internal-biochar-lot-0527.jpg", materialFile: "biochar-bags.jpg", note: "ล็อตผลิตภายใน", isNewItem: false },
  { id: "INV-FLX-004", recordDate: "2026-05-26", transactionType: "เบิกใช้", category: "วัสดุปลูก", itemName: "ไบโอชา", details: "ผสมดินปลูกทดลองสูตร GS-03", quantity: 310, unit: "กิโลกรัม", unitPrice: 18, supplier: "", requester: "คุณหวาน", usagePurpose: "ทดลองปรับปรุงดิน", plot: "แปลงทดลอง B1", warehouse: "คลังชีวภัณฑ์", recorder: "คุณหวาน", status: "ใกล้หมด", countStock: "ต้องนับสต็อก", minimumStock: 150, receiptFile: "", materialFile: "biochar-field-test.jpg", note: "ใช้กับ R&D สูตร GS-03", isNewItem: false },
  { id: "INV-FLX-005", recordDate: "2026-05-27", transactionType: "นำเข้า", category: "ระบบน้ำ / อะไหล่", itemName: "หัวน้ำหยด", details: "หัวน้ำหยด 8 ลิตร/ชม. สำหรับซ่อมระบบน้ำ", quantity: 600, unit: "ชิ้น", unitPrice: 4.5, supplier: "ร้านระบบน้ำโคกเจริญ", requester: "", usagePurpose: "อะไหล่ซ่อมระบบน้ำ", plot: "แปลง A-C", warehouse: "คลังอะไหล่ระบบน้ำ", recorder: "พี่สมชาย", status: "ใช้งานได้", countStock: "ต้องนับสต็อก", minimumStock: 120, receiptFile: "dripper-bill.jpg", materialFile: "dripper-box.jpg", note: "แพ็กละ 100 ชิ้น", isNewItem: false },
  { id: "INV-FLX-006", recordDate: "2026-05-27", transactionType: "เบิกใช้", category: "ระบบน้ำ / อะไหล่", itemName: "หัวน้ำหยด", details: "เปลี่ยนหัวน้ำหยดที่อุดตัน", quantity: 210, unit: "ชิ้น", unitPrice: 4.5, supplier: "", requester: "พี่สมชาย", usagePurpose: "ซ่อมระบบน้ำ", plot: "แปลง B2-B8", warehouse: "คลังอะไหล่ระบบน้ำ", recorder: "คุณหวาน", status: "ใช้งานได้", countStock: "ต้องนับสต็อก", minimumStock: 120, receiptFile: "", materialFile: "dripper-repair.jpg", note: "ซ่อมแล้วแรงดันปกติ", isNewItem: false },
  { id: "INV-FLX-007", recordDate: "2026-05-27", transactionType: "นำเข้า", category: "เมล็ดพันธุ์ / กิ่งพันธุ์", itemName: "มันญี่ปุ่น", details: "กิ่งพันธุ์ชุดทดลอง R&D 4 สายพันธุ์", quantity: 80, unit: "กิ่ง", unitPrice: 12, supplier: "แปลงทดลองพันธุ์มัน", requester: "", usagePurpose: "ทดลองปลูกมันญี่ปุ่น", plot: "แปลง R&D", warehouse: "โรงเพาะชำ", recorder: "คุณหวาน", status: "ใช้งานได้", countStock: "ต้องนับสต็อก", minimumStock: 20, receiptFile: "sweet-potato-cuttings.jpg", materialFile: "rd-cuttings.jpg", note: "แยกสีพันธุ์ชัดเจน", isNewItem: false },
  { id: "INV-FLX-008", recordDate: "2026-05-27", transactionType: "นำเข้า", category: "อุปกรณ์การเกษตร", itemName: "เครื่องตัดหญ้า", details: "เครื่องตัดหญ้า Honda รุ่น GX35", quantity: 2, unit: "ชิ้น", unitPrice: 12500, supplier: "ศูนย์เครื่องมือเกษตร", requester: "", usagePurpose: "เพิ่มกำลังทีมงานภาคสนาม", plot: "ทุกแปลง", warehouse: "คลังอุปกรณ์", recorder: "Admin Farm", status: "ใช้งานได้", countStock: "ไม่ต้องนับสต็อก", minimumStock: 0, receiptFile: "grass-cutter-bill.jpg", materialFile: "grass-cutter.jpg", note: "บันทึกเป็นทรัพย์สินและติด QR", isNewItem: false },
  { id: "INV-FLX-009", recordDate: "2026-05-27", transactionType: "เสียหาย", category: "อุปกรณ์การเกษตร", itemName: "เครื่องตัดหญ้า", details: "ใบมีดสั่นผิดปกติ ต้องรอซ่อม", quantity: 1, unit: "ชิ้น", unitPrice: 0, supplier: "", requester: "พี่ไกร", usagePurpose: "แจ้งซ่อมบำรุง", plot: "Zone 6", warehouse: "คลังอุปกรณ์", recorder: "พี่ไกร", status: "รอซ่อม", countStock: "ไม่ต้องนับสต็อก", minimumStock: 0, receiptFile: "", materialFile: "grass-cutter-problem.jpg", note: "ส่งเข้ารอบ PM", isNewItem: false },
  { id: "INV-FLX-010", recordDate: "2026-05-27", transactionType: "นำเข้า", category: "บรรจุภัณฑ์ / ถุง / กระสอบ", itemName: "กล่องแพ็กสินค้า", details: "กล่องส่งสินค้าออนไลน์ ขนาด M ลาย GoodSeed Farm", quantity: 300, unit: "ใบ", unitPrice: 14, supplier: "โรงงานบรรจุภัณฑ์", requester: "", usagePurpose: "เตรียมขายออนไลน์", plot: "คลังสินค้าออนไลน์", warehouse: "คลังแพ็กสินค้า", recorder: "Admin Farm", status: "ใช้งานได้", countStock: "ต้องนับสต็อก", minimumStock: 60, receiptFile: "packaging-bill.jpg", materialFile: "goodseed-box.jpg", note: "รองรับ Shopee / Lazada", isNewItem: true },
  { id: "INV-FLX-011", recordDate: "2026-05-27", transactionType: "ปรับยอด", category: "อุปกรณ์สำนักงาน", itemName: "สมุดบันทึกงาน", details: "สมุดบันทึกงานประจำวันสำหรับหัวหน้างาน", quantity: 24, unit: "เล่ม", unitPrice: 35, supplier: "ร้านเครื่องเขียน", requester: "", usagePurpose: "ใช้กับแบบฟอร์มภาคสนาม", plot: "สำนักงานฟาร์ม", warehouse: "ออฟฟิศ", recorder: "น.ส.รุ่งนภา", status: "ใช้งานได้", countStock: "ต้องนับสต็อก", minimumStock: 6, receiptFile: "", materialFile: "field-notebook.jpg", note: "เพิ่มรายการใหม่ในระบบ", isNewItem: true },
];

function getFlexibleCategory(categoryName) {
  return flexibleInventoryCategories.find((category) => category.name === categoryName) || flexibleInventoryCategories[0];
}

function flexibleInventoryKey(item) {
  return `${item.category}::${item.itemName}::${item.unit}`;
}

function getInventoryQuantities(item) {
  if (item.countStock === "ไม่ต้องนับสต็อก") {
    return { inQty: 0, outQty: 0 };
  }
  if (["นำเข้า", "ปรับยอด", "คืนของ"].includes(item.transactionType)) {
    return { inQty: Number(item.quantity) || 0, outQty: 0 };
  }
  if (["เบิกใช้", "เสียหาย"].includes(item.transactionType)) {
    return { inQty: 0, outQty: Number(item.quantity) || 0 };
  }
  return { inQty: 0, outQty: 0 };
}

function buildFlexibleInventoryStockRows(transactions) {
  const grouped = transactions.reduce((acc, item) => {
    const key = flexibleInventoryKey(item);
    const qty = getInventoryQuantities(item);
    if (!acc[key]) {
      acc[key] = {
        key,
        category: item.category,
        itemName: item.itemName,
        unit: item.unit,
        details: item.details,
        inQty: 0,
        outQty: 0,
        unitPrice: Number(item.unitPrice) || 0,
        minimumStock: Number(item.minimumStock) || 0,
        countStock: item.countStock,
        status: item.status,
        lastUpdated: item.recordDate,
        warehouse: item.warehouse,
        isNewItem: item.isNewItem,
      };
    }
    acc[key].inQty += qty.inQty;
    acc[key].outQty += qty.outQty;
    acc[key].unitPrice = Number(item.unitPrice) || acc[key].unitPrice;
    acc[key].minimumStock = Number(item.minimumStock) || acc[key].minimumStock;
    acc[key].countStock = item.countStock;
    acc[key].status = item.status || acc[key].status;
    acc[key].details = item.details || acc[key].details;
    acc[key].warehouse = item.warehouse || acc[key].warehouse;
    acc[key].isNewItem = acc[key].isNewItem || item.isNewItem;
    acc[key].lastUpdated = item.recordDate > acc[key].lastUpdated ? item.recordDate : acc[key].lastUpdated;
    return acc;
  }, {});

  return Object.values(grouped).map((row) => {
    const remaining = row.countStock === "ต้องนับสต็อก" ? Math.max(0, row.inQty - row.outQty) : row.inQty;
    const computedStatus =
      row.countStock === "ไม่ต้องนับสต็อก"
        ? row.status
        : remaining <= 0
          ? "หมด"
          : remaining <= row.minimumStock
            ? "ใกล้หมด"
            : row.status === "ชำรุด" || row.status === "สูญหาย" || row.status === "รอซ่อม"
              ? row.status
              : "ใช้งานได้";
    return {
      ...row,
      remaining,
      status: computedStatus,
      stockValue: remaining * row.unitPrice,
    };
  });
}

function MaterialStatusBadge({ status }) {
  return <Badge className={flexibleInventoryStatusClasses[status] || "bg-slate-100 text-slate-700 ring-slate-200"}>{status}</Badge>;
}

function TransactionTypeBadge({ type }) {
  return <Badge className={flexibleTransactionClasses[type] || "bg-slate-100 text-slate-700 ring-slate-200"}>{type}</Badge>;
}

function InventoryWarehousePage({ role = "owner" }) {
  const initialCategory = flexibleInventoryCategories[0];
  const [transactions, setTransactions] = useState(initialFlexibleInventoryTransactions);
  const [notice, setNotice] = useState("");
  const [filters, setFilters] = useState({ query: "", category: "ทั้งหมด", date: "", plot: "", requester: "", status: "ทั้งหมด" });
  const [form, setForm] = useState({
    recordDate: "2026-05-27",
    transactionType: "นำเข้า",
    category: initialCategory.name,
    itemName: initialCategory.items[0],
    customItemName: "",
    details: "ระบุยี่ห้อ รุ่น ขนาด สูตรปุ๋ย ความเข้มข้น วันหมดอายุ สภาพของวัสดุ หรือเหตุผลที่เบิกใช้",
    quantity: 1,
    unit: initialCategory.defaultUnit,
    unitPrice: 0,
    supplier: "",
    requester: "",
    usagePurpose: "",
    plot: "",
    warehouse: "คลังกลาง",
    receiptFile: "",
    materialFile: "",
    note: "",
    countStock: initialCategory.countStock,
    status: "ใช้งานได้",
    recorder: "คุณหวาน",
    minimumStock: 10,
  });

  const canSubmit = isOwnerRole(role) || ["admin", "manager", "staff"].includes(role);
  const canEdit = isOwnerRole(role) || ["admin", "manager"].includes(role);
  const canExport = isOwnerRole(role) || ["admin", "manager"].includes(role);
  const roleLabel = roleInfo(role).label;
  const allowedTransactionTypes = role === "staff" ? ["นำเข้า", "เบิกใช้"] : flexibleInventoryTransactionTypes;
  const selectedCategory = getFlexibleCategory(form.category);
  const itemChoices = selectedCategory.items.includes("อื่น ๆ ระบุเอง") ? selectedCategory.items : [...selectedCategory.items, "อื่น ๆ ระบุเอง"];
  const displayItemName = form.itemName === "อื่น ๆ ระบุเอง" ? form.customItemName.trim() : form.itemName;
  const totalValue = (Number(form.quantity) || 0) * (Number(form.unitPrice) || 0);

  const stockRows = buildFlexibleInventoryStockRows(transactions);
  const stockByKey = new Map(stockRows.map((row) => [row.key, row]));
  const today = "2026-05-27";
  const filteredTransactions = transactions.filter((item) => {
    const query = filters.query.trim().toLowerCase();
    const queryMatch = !query || [item.itemName, item.category, item.details, item.note, item.recorder, item.requester, item.plot].join(" ").toLowerCase().includes(query);
    return (
      queryMatch &&
      (filters.category === "ทั้งหมด" || item.category === filters.category) &&
      (!filters.date || item.recordDate === filters.date) &&
      (!filters.plot || item.plot.toLowerCase().includes(filters.plot.toLowerCase())) &&
      (!filters.requester || item.requester.toLowerCase().includes(filters.requester.toLowerCase())) &&
      (filters.status === "ทั้งหมด" || item.status === filters.status)
    );
  });

  const importsToday = transactions.filter((item) => item.recordDate === today && item.transactionType === "นำเข้า").length;
  const withdrawalsToday = transactions.filter((item) => item.recordDate === today && item.transactionType === "เบิกใช้").length;
  const lowStockRows = stockRows.filter((item) => item.status === "ใกล้หมด");
  const outStockRows = stockRows.filter((item) => item.status === "หมด");
  const stockValue = stockRows.filter((item) => item.countStock === "ต้องนับสต็อก").reduce((sum, item) => sum + item.stockValue, 0);
  const newItemCount = transactions.filter((item) => item.isNewItem).length;
  const countStockRows = stockRows.filter((item) => item.countStock === "ต้องนับสต็อก").length;
  const noCountRows = stockRows.filter((item) => item.countStock === "ไม่ต้องนับสต็อก").length;

  const updateForm = (patch) => setForm((current) => ({ ...current, ...patch }));

  const handleCategoryChange = (categoryName) => {
    const nextCategory = getFlexibleCategory(categoryName);
    updateForm({
      category: categoryName,
      itemName: nextCategory.items[0] || "อื่น ๆ ระบุเอง",
      customItemName: "",
      unit: nextCategory.defaultUnit,
      countStock: nextCategory.countStock,
    });
  };

  const saveTransaction = (event) => {
    event.preventDefault();
    if (!canSubmit) return;
    const itemName = displayItemName || "รายการใหม่";
    const transactionType = allowedTransactionTypes.includes(form.transactionType) ? form.transactionType : allowedTransactionTypes[0];
    const nextTransaction = {
      id: `INV-FLX-${String(Date.now()).slice(-6)}`,
      ...form,
      transactionType,
      itemName,
      quantity: Number(form.quantity) || 0,
      unitPrice: Number(form.unitPrice) || 0,
      minimumStock: Number(form.minimumStock) || 0,
      isNewItem: form.itemName === "อื่น ๆ ระบุเอง" || !selectedCategory.items.includes(itemName),
    };
    setTransactions((items) => [nextTransaction, ...items]);
    setNotice(`บันทึกรายการ "${itemName}" เรียบร้อยแล้ว และอัปเดต Dashboard Inventory ทันที`);
    updateForm({ customItemName: "", quantity: 1, unitPrice: 0, supplier: "", requester: "", usagePurpose: "", receiptFile: "", materialFile: "", note: "" });
  };

  const exportCsv = () => {
    const headers = ["วันที่", "ประเภทการทำรายการ", "หมวดหมู่", "ชื่อรายการ", "รายละเอียด", "จำนวนเข้า", "จำนวนออก", "คงเหลือ", "หน่วย", "มูลค่า", "ผู้บันทึก", "ผู้เบิก", "แปลง/โซน", "สถานะ", "รูป/เอกสารแนบ", "หมายเหตุ"];
    const rows = filteredTransactions.map((item) => {
      const qty = getInventoryQuantities(item);
      const stock = stockByKey.get(flexibleInventoryKey(item));
      return [
        item.recordDate,
        item.transactionType,
        item.category,
        item.itemName,
        item.details,
        qty.inQty || "",
        qty.outQty || "",
        stock?.countStock === "ต้องนับสต็อก" ? stock.remaining : "Asset",
        item.unit,
        ((qty.inQty || qty.outQty || Number(item.quantity) || 0) * (Number(item.unitPrice) || 0)).toLocaleString("th-TH"),
        item.recorder,
        item.requester || "-",
        item.plot || "-",
        item.status,
        [item.receiptFile, item.materialFile].filter(Boolean).join(" / ") || "-",
        item.note || "-",
      ];
    });
    const csv = [headers, ...rows].map((row) => row.map((cell) => `"${String(cell).replaceAll('"', '""')}"`).join(",")).join("\n");
    downloadFile("goodseed-inventory-flexible-transactions.csv", `\ufeff${csv}`, "text/csv;charset=utf-8");
  };
  const buildFlexibleInventoryExportRows = () => {
    const headers = ["วันที่", "ประเภทการทำรายการ", "หมวดหมู่", "ชื่อรายการ", "รายละเอียด", "จำนวนเข้า", "จำนวนออก", "คงเหลือ", "หน่วย", "มูลค่า", "ผู้บันทึก", "ผู้เบิก", "แปลง/โซน", "สถานะ", "รูป/เอกสารแนบ", "หมายเหตุ"];
    const rows = filteredTransactions.map((item) => {
      const qty = getInventoryQuantities(item);
      const stock = stockByKey.get(flexibleInventoryKey(item));
      return [
        item.recordDate,
        item.transactionType,
        item.category,
        item.itemName,
        item.details,
        qty.inQty || "",
        qty.outQty || "",
        stock?.countStock === "ต้องนับสต็อก" ? stock.remaining : "Asset",
        item.unit,
        ((qty.inQty || qty.outQty || Number(item.quantity) || 0) * (Number(item.unitPrice) || 0)).toLocaleString("th-TH"),
        item.recorder,
        item.requester || "-",
        item.plot || "-",
        item.status,
        [item.receiptFile, item.materialFile].filter(Boolean).join(" / ") || "-",
        item.note || "-",
      ];
    });
    return { headers, rows };
  };
  const exportFlexibleInventoryExcel = () => {
    const { headers, rows } = buildFlexibleInventoryExportRows();
    const htmlRows = [headers, ...rows].map((row) => `<tr>${row.map((cell) => `<td>${String(cell ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")}</td>`).join("")}</tr>`).join("");
    const html = `<html><meta charset="utf-8"><body><table border="1">${htmlRows}</table></body></html>`;
    downloadFile("goodseed-inventory-flexible-transactions.xls", html, "application/vnd.ms-excel;charset=utf-8");
  };
  const exportFlexibleInventoryWord = () => {
    const { headers, rows } = buildFlexibleInventoryExportRows();
    const htmlRows = [headers, ...rows].map((row) => `<tr>${row.map((cell) => `<td>${String(cell ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")}</td>`).join("")}</tr>`).join("");
    const html = `<html><meta charset="utf-8"><body><h1>GOODSEED Flexible Material Transaction Report</h1><p>Generated: ${new Date().toLocaleString("th-TH")}</p><table border="1" cellspacing="0" cellpadding="6">${htmlRows}</table></body></html>`;
    downloadFile("goodseed-inventory-flexible-transactions.doc", html, "application/msword;charset=utf-8");
  };
  const exportFlexibleInventoryPdf = () => {
    const { headers, rows } = buildFlexibleInventoryExportRows();
    const htmlRows = [headers, ...rows].map((row) => `<tr>${row.map((cell) => `<td>${String(cell ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")}</td>`).join("")}</tr>`).join("");
    const html = `<html><meta charset="utf-8"><body><h1>GOODSEED Flexible Material Transaction Report</h1><p>ใช้ไฟล์นี้เปิดแล้วสั่ง Print / Save as PDF ได้</p><table border="1" cellspacing="0" cellpadding="6">${htmlRows}</table></body></html>`;
    downloadFile("goodseed-inventory-flexible-report-pdf.html", html, "text/html;charset=utf-8");
  };

  const inputClass = "mt-2 w-full rounded-lg border border-goodseed-200 bg-white px-3 py-2.5 text-sm font-semibold text-goodseed-900 outline-none focus:ring-2 focus:ring-goodseed-300";
  const labelClass = "text-sm font-extrabold text-goodseed-800";

  return (
    <section id="inventory" className="space-y-5">
      <SectionHeader
        title="Inventory / Warehouse"
        subtitle="ระบบบันทึกวัสดุนำเข้า เบิกใช้ ปรับยอด และติดตามคงเหลือแบบยืดหยุ่น เพิ่มรายการใหม่เองได้ พร้อมแยกวัสดุสิ้นเปลืองออกจากทรัพย์สิน/อุปกรณ์"
        action={
          <div className="flex flex-wrap gap-2">
            <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Role: {roleLabel}</Badge>
            {canExport && <button onClick={exportCsv} className="inline-flex items-center gap-2 rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white shadow-soft hover:bg-goodseed-800"><Icon name="download" className="h-4 w-4" /> Export CSV</button>}
          </div>
        }
      />

      <CrudGovernanceBar role={role} moduleId="inventory" title="Inventory / Warehouse CRUD" />

      {notice && (
        <div className="flex items-start justify-between gap-3 rounded-lg border border-goodseed-200 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-800 shadow-soft">
          <span>{notice}</span>
          <button onClick={() => setNotice("")} className="rounded-full p-1 text-goodseed-700 hover:bg-goodseed-100"><Icon name="x" className="h-4 w-4" /></button>
        </div>
      )}

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <DashboardCard label="วัสดุนำเข้าวันนี้" value={importsToday} unit="รายการ" icon="upload" tone="bg-goodseed-100 text-goodseed-800" />
        <DashboardCard label="วัสดุเบิกใช้วันนี้" value={withdrawalsToday} unit="รายการ" icon="download" tone="bg-orange-100 text-orange-700" />
        <DashboardCard label="รายการใกล้หมด" value={lowStockRows.length} unit="รายการ" icon="bell" tone="bg-amber-100 text-amber-700" />
        <DashboardCard label="รายการหมดสต็อก" value={outStockRows.length} unit="รายการ" icon="x" tone="bg-red-100 text-red-700" />
        <DashboardCard label="มูลค่าวัสดุคงเหลือ" value={stockValue.toLocaleString("th-TH")} unit="บาท" icon="money" tone="bg-emerald-100 text-emerald-800" />
        <DashboardCard label="รายการที่เพิ่มใหม่" value={newItemCount} unit="รายการ" icon="check" tone="bg-sky-100 text-sky-700" />
        <DashboardCard label="ต้องตรวจนับสต็อก" value={countStockRows} unit="รายการ" icon="box" tone="bg-goodseed-100 text-goodseed-800" />
        <DashboardCard label="ไม่ต้องนับสต็อก" value={noCountRows} unit="ทรัพย์สิน" icon="assets" tone="bg-purple-100 text-purple-700" />
      </div>

      <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
        <main className="space-y-6">
          <DashboardPanel
            id="inventory-flexible-form"
            title="Flexible Material Transaction Form / ฟอร์มบันทึกวัสดุแบบยืดหยุ่น"
            action={
              <div className="flex flex-wrap gap-2">
                <button type="button" onClick={exportFlexibleInventoryPdf} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="download" className="h-4 w-4" />PDF</button>
                <button type="button" onClick={exportFlexibleInventoryExcel} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="download" className="h-4 w-4" />Excel</button>
                <button type="button" onClick={exportCsv} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="download" className="h-4 w-4" />CSV</button>
                <button type="button" onClick={exportFlexibleInventoryWord} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800 hover:bg-goodseed-50"><Icon name="file" className="h-4 w-4" />Word</button>
                <button type="button" onClick={() => window.print()} className="inline-flex items-center gap-2 rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white hover:bg-goodseed-800"><Icon name="file" className="h-4 w-4" />Print</button>
              </div>
            }
          >
            <form onSubmit={saveTransaction} className="space-y-5">
              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                <label><span className={labelClass}>วันที่บันทึก</span><input type="date" value={form.recordDate} onChange={(event) => updateForm({ recordDate: event.target.value })} className={inputClass} /></label>
                <label><span className={labelClass}>ประเภทการทำรายการ</span><select value={allowedTransactionTypes.includes(form.transactionType) ? form.transactionType : allowedTransactionTypes[0]} onChange={(event) => updateForm({ transactionType: event.target.value })} className={inputClass}>{allowedTransactionTypes.map((type) => <option key={type}>{type}</option>)}</select></label>
                <label><span className={labelClass}>หมวดหมู่วัสดุ</span><select value={form.category} onChange={(event) => handleCategoryChange(event.target.value)} className={inputClass}>{flexibleInventoryCategories.map((category) => <option key={category.name}>{category.name}</option>)}</select></label>
                <label><span className={labelClass}>ชื่อรายการ</span><select value={form.itemName} onChange={(event) => updateForm({ itemName: event.target.value })} className={inputClass}>{itemChoices.map((item) => <option key={item}>{item}</option>)}</select></label>
              </div>

              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                <label className={form.itemName === "อื่น ๆ ระบุเอง" ? "" : "opacity-70"}><span className={labelClass}>อื่น ๆ / ระบุรายการเอง</span><input value={form.customItemName} onChange={(event) => updateForm({ customItemName: event.target.value })} placeholder="พิมพ์ชื่อวัสดุใหม่ เช่น ผ้าคลุมแปลง UV" className={inputClass} disabled={form.itemName !== "อื่น ๆ ระบุเอง"} /></label>
                <label><span className={labelClass}>จำนวน</span><input type="number" min="0" step="0.01" value={form.quantity} onChange={(event) => updateForm({ quantity: event.target.value })} className={inputClass} /></label>
                <label><span className={labelClass}>หน่วยนับ</span><select value={form.unit} onChange={(event) => updateForm({ unit: event.target.value })} className={inputClass}>{flexibleInventoryUnits.map((unit) => <option key={unit}>{unit}</option>)}</select></label>
                <label><span className={labelClass}>ราคาต่อหน่วย</span><input type="number" min="0" step="0.01" value={form.unitPrice} onChange={(event) => updateForm({ unitPrice: event.target.value })} className={inputClass} /></label>
              </div>

              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                <label><span className={labelClass}>มูลค่ารวม</span><input value={`${totalValue.toLocaleString("th-TH")} บาท`} readOnly className={`${inputClass} bg-goodseed-50 text-goodseed-900`} /></label>
                <label><span className={labelClass}>ต้องนับสต็อกหรือไม่</span><select value={form.countStock} onChange={(event) => updateForm({ countStock: event.target.value })} className={inputClass}>{flexibleInventoryStockModes.map((mode) => <option key={mode}>{mode}</option>)}</select></label>
                <label><span className={labelClass}>สถานะวัสดุ</span><select value={form.status} onChange={(event) => updateForm({ status: event.target.value })} className={inputClass}>{flexibleInventoryStatuses.map((status) => <option key={status}>{status}</option>)}</select></label>
                <label><span className={labelClass}>Minimum Stock</span><input type="number" min="0" step="0.01" value={form.minimumStock} onChange={(event) => updateForm({ minimumStock: event.target.value })} className={inputClass} /></label>
              </div>

              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                <label><span className={labelClass}>ผู้ขาย / แหล่งที่มา</span><input value={form.supplier} onChange={(event) => updateForm({ supplier: event.target.value })} placeholder="Supplier / แหล่งที่มา" className={inputClass} /></label>
                <label><span className={labelClass}>ผู้เบิกใช้</span><input value={form.requester} onChange={(event) => updateForm({ requester: event.target.value })} placeholder="ชื่อผู้เบิกใช้" className={inputClass} /></label>
                <label><span className={labelClass}>ผู้บันทึก</span><input value={form.recorder} onChange={(event) => updateForm({ recorder: event.target.value })} placeholder="ชื่อผู้บันทึก" className={inputClass} /></label>
                <label><span className={labelClass}>ใช้กับงานอะไร</span><input value={form.usagePurpose} onChange={(event) => updateForm({ usagePurpose: event.target.value })} placeholder="เช่น ใส่ปุ๋ย ซ่อมระบบน้ำ R&D" className={inputClass} /></label>
                <label><span className={labelClass}>ใช้กับแปลงไหน / โซนไหน</span><input value={form.plot} onChange={(event) => updateForm({ plot: event.target.value })} placeholder="เช่น แปลง A1-A10 / Zone 6" className={inputClass} /></label>
                <label><span className={labelClass}>คลังจัดเก็บ</span><input value={form.warehouse} onChange={(event) => updateForm({ warehouse: event.target.value })} placeholder="เช่น คลังกลาง / โรงเพาะชำ" className={inputClass} /></label>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <label><span className={labelClass}>รายละเอียดเพิ่มเติม</span><textarea value={form.details} onChange={(event) => updateForm({ details: event.target.value })} rows="4" className={`${inputClass} resize-none leading-6`} /></label>
                <label><span className={labelClass}>หมายเหตุ</span><textarea value={form.note} onChange={(event) => updateForm({ note: event.target.value })} rows="4" placeholder="หมายเหตุเพิ่มเติม เช่น สภาพวัสดุ เหตุผลที่เบิกใช้ หรือข้อควรตรวจสอบ" className={`${inputClass} resize-none leading-6`} /></label>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <label className="rounded-lg border-2 border-dashed border-goodseed-200 bg-goodseed-50 p-4">
                  <span className="flex items-center gap-2 text-sm font-extrabold text-goodseed-800"><Icon name="camera" className="h-4 w-4" /> แนบรูปใบเสร็จ</span>
                  <input type="file" accept="image/*,.pdf" onChange={(event) => updateForm({ receiptFile: event.target.files?.[0]?.name || "" })} className="mt-3 w-full text-sm font-semibold text-goodseed-800" />
                  <p className="mt-2 text-xs font-bold text-goodseed-600">{form.receiptFile || "ยังไม่ได้เลือกไฟล์"}</p>
                </label>
                <label className="rounded-lg border-2 border-dashed border-goodseed-200 bg-goodseed-50 p-4">
                  <span className="flex items-center gap-2 text-sm font-extrabold text-goodseed-800"><Icon name="camera" className="h-4 w-4" /> แนบรูปวัสดุ</span>
                  <input type="file" accept="image/*" onChange={(event) => updateForm({ materialFile: event.target.files?.[0]?.name || "" })} className="mt-3 w-full text-sm font-semibold text-goodseed-800" />
                  <p className="mt-2 text-xs font-bold text-goodseed-600">{form.materialFile || "ยังไม่ได้เลือกไฟล์"}</p>
                </label>
              </div>

              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <button type="button" onClick={() => updateForm({ itemName: "อื่น ๆ ระบุเอง", customItemName: "" })} className="inline-flex items-center justify-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50">
                  <Icon name="check" className="h-4 w-4" /> + เพิ่มรายการใหม่
                </button>
                <button type="submit" disabled={!canSubmit} className="inline-flex items-center justify-center gap-2 rounded-lg bg-goodseed-700 px-6 py-3 text-sm font-extrabold text-white shadow-soft hover:bg-goodseed-800 disabled:cursor-not-allowed disabled:bg-slate-300">
                  <Icon name="upload" className="h-4 w-4" /> บันทึกรายการ
                </button>
              </div>
            </form>
          </DashboardPanel>

          <DashboardPanel id="inventory-category-samples" title="หมวดหมู่และตัวอย่างรายการ / Category Samples">
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {flexibleInventoryCategories.map((category) => (
                <div key={category.name} className="rounded-lg border border-goodseed-100 bg-goodseed-50/60 p-4">
                  <div className="mb-3 flex items-start justify-between gap-3">
                    <div>
                      <p className="text-sm font-extrabold text-goodseed-950">{category.name}</p>
                      <p className="mt-1 text-xs font-bold text-goodseed-600">{category.countStock}</p>
                    </div>
                    <Icon name={category.countStock === "ต้องนับสต็อก" ? "box" : "assets"} className="h-5 w-5 text-goodseed-700" />
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {category.items.map((item) => <Badge key={item} className="bg-white text-goodseed-800 ring-goodseed-100">{item}</Badge>)}
                  </div>
                </div>
              ))}
            </div>
          </DashboardPanel>

          <DashboardPanel
            id="inventory-transactions"
            title="Inventory Transaction Table / ตารางรายการวัสดุ"
            action={<Badge className="bg-white text-goodseed-800 ring-goodseed-200">{filteredTransactions.length} รายการ</Badge>}
          >
            <div className="mb-4 grid gap-3 md:grid-cols-2 xl:grid-cols-6">
              <input value={filters.query} onChange={(event) => setFilters((current) => ({ ...current, query: event.target.value }))} placeholder="Search Materials" className={inputClass} />
              <select value={filters.category} onChange={(event) => setFilters((current) => ({ ...current, category: event.target.value }))} className={inputClass}>
                {["ทั้งหมด", ...flexibleInventoryCategories.map((category) => category.name)].map((category) => <option key={category}>{category}</option>)}
              </select>
              <input type="date" value={filters.date} onChange={(event) => setFilters((current) => ({ ...current, date: event.target.value }))} className={inputClass} />
              <input value={filters.plot} onChange={(event) => setFilters((current) => ({ ...current, plot: event.target.value }))} placeholder="แปลง / โซน" className={inputClass} />
              <input value={filters.requester} onChange={(event) => setFilters((current) => ({ ...current, requester: event.target.value }))} placeholder="ผู้เบิก" className={inputClass} />
              <select value={filters.status} onChange={(event) => setFilters((current) => ({ ...current, status: event.target.value }))} className={inputClass}>
                {["ทั้งหมด", ...flexibleInventoryStatuses].map((status) => <option key={status}>{status}</option>)}
              </select>
            </div>

            <div className="hidden overflow-x-auto lg:block">
              <table className="min-w-[1320px] w-full border-separate border-spacing-y-2 text-left text-sm">
                <thead>
                  <tr className="text-xs font-extrabold uppercase tracking-wide text-goodseed-700">
                    {["วันที่", "ประเภทการทำรายการ", "หมวดหมู่", "ชื่อรายการ", "รายละเอียด", "จำนวนเข้า", "จำนวนออก", "คงเหลือ", "หน่วย", "มูลค่า", "ผู้บันทึก", "ผู้เบิก", "แปลง/โซน", "สถานะ", "รูป/เอกสารแนบ", "หมายเหตุ"].map((head) => <th key={head} className="bg-goodseed-50 px-3 py-3 first:rounded-l-lg last:rounded-r-lg">{head}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {filteredTransactions.map((item) => {
                    const qty = getInventoryQuantities(item);
                    const stock = stockByKey.get(flexibleInventoryKey(item));
                    const rowValue = (qty.inQty || qty.outQty || Number(item.quantity) || 0) * (Number(item.unitPrice) || 0);
                    return (
                      <tr key={item.id} className="align-top">
                        <td className="rounded-l-lg bg-white px-3 py-3 font-bold text-goodseed-800 shadow-sm">{item.recordDate}</td>
                        <td className="bg-white px-3 py-3 shadow-sm"><TransactionTypeBadge type={item.transactionType} /></td>
                        <td className="bg-white px-3 py-3 font-bold text-goodseed-800 shadow-sm">{item.category}</td>
                        <td className="bg-white px-3 py-3 font-extrabold text-goodseed-950 shadow-sm">{item.itemName}</td>
                        <td className="max-w-[260px] bg-white px-3 py-3 leading-6 text-goodseed-700 shadow-sm">{item.details}</td>
                        <td className="bg-white px-3 py-3 font-extrabold text-goodseed-900 shadow-sm">{qty.inQty || "-"}</td>
                        <td className="bg-white px-3 py-3 font-extrabold text-goodseed-900 shadow-sm">{qty.outQty || "-"}</td>
                        <td className="bg-white px-3 py-3 font-extrabold text-goodseed-950 shadow-sm">{stock?.countStock === "ต้องนับสต็อก" ? stock.remaining.toLocaleString("th-TH") : "Asset"}</td>
                        <td className="bg-white px-3 py-3 font-bold text-goodseed-700 shadow-sm">{item.unit}</td>
                        <td className="bg-white px-3 py-3 font-extrabold text-goodseed-950 shadow-sm">{rowValue.toLocaleString("th-TH")}</td>
                        <td className="bg-white px-3 py-3 font-bold text-goodseed-800 shadow-sm">{item.recorder}</td>
                        <td className="bg-white px-3 py-3 font-bold text-goodseed-700 shadow-sm">{item.requester || "-"}</td>
                        <td className="bg-white px-3 py-3 font-bold text-goodseed-700 shadow-sm">{item.plot || "-"}</td>
                        <td className="bg-white px-3 py-3 shadow-sm"><MaterialStatusBadge status={item.status} /></td>
                        <td className="bg-white px-3 py-3 text-xs font-bold text-goodseed-700 shadow-sm">{[item.receiptFile, item.materialFile].filter(Boolean).join(" / ") || "-"}</td>
                        <td className="rounded-r-lg bg-white px-3 py-3 leading-6 text-goodseed-700 shadow-sm">{item.note || "-"}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            <div className="space-y-3 lg:hidden">
              {filteredTransactions.map((item) => {
                const qty = getInventoryQuantities(item);
                const stock = stockByKey.get(flexibleInventoryKey(item));
                return (
                  <div key={item.id} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <div>
                        <p className="text-base font-extrabold text-goodseed-950">{item.itemName}</p>
                        <p className="mt-1 text-xs font-bold text-goodseed-600">{item.category} • {item.recordDate}</p>
                      </div>
                      <TransactionTypeBadge type={item.transactionType} />
                    </div>
                    <p className="mt-3 text-sm font-semibold leading-6 text-goodseed-700">{item.details}</p>
                    <div className="mt-3 grid grid-cols-2 gap-2 text-sm font-bold text-goodseed-800">
                      <span>เข้า: {qty.inQty || "-"}</span>
                      <span>ออก: {qty.outQty || "-"}</span>
                      <span>คงเหลือ: {stock?.countStock === "ต้องนับสต็อก" ? stock.remaining : "Asset"}</span>
                      <span>หน่วย: {item.unit}</span>
                    </div>
                    <div className="mt-3 flex flex-wrap gap-2"><MaterialStatusBadge status={item.status} /><Badge className="bg-goodseed-50 text-goodseed-800 ring-goodseed-100">{item.plot || "ไม่ระบุแปลง"}</Badge></div>
                  </div>
                );
              })}
            </div>
          </DashboardPanel>

          <DashboardPanel id="inventory-stock-snapshot" title="บันทึกยอดคงเหลือ / Current Stock Snapshot">
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {stockRows.map((row) => (
                <div key={row.key} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <p className="text-sm font-extrabold text-goodseed-950">{row.itemName}</p>
                      <p className="mt-1 text-xs font-bold text-goodseed-600">{row.category}</p>
                    </div>
                    <MaterialStatusBadge status={row.status} />
                  </div>
                  <div className="mt-4 grid grid-cols-2 gap-2 text-sm font-bold text-goodseed-800">
                    <span>นำเข้า: {row.inQty.toLocaleString("th-TH")} {row.unit}</span>
                    <span>เบิกใช้: {row.outQty.toLocaleString("th-TH")} {row.unit}</span>
                    <span>คงเหลือ: {row.countStock === "ต้องนับสต็อก" ? row.remaining.toLocaleString("th-TH") : "บันทึกเป็นทรัพย์สิน"}</span>
                    <span>ขั้นต่ำ: {row.minimumStock.toLocaleString("th-TH")}</span>
                  </div>
                  <p className="mt-3 text-xs font-semibold leading-5 text-goodseed-600">{row.details}</p>
                </div>
              ))}
            </div>
          </DashboardPanel>
        </main>

        <aside className="space-y-6">
          <DashboardPanel id="inventory-alerts" title="Alerts / Notifications">
            <div className="space-y-3">
              {[...lowStockRows, ...outStockRows].slice(0, 6).map((item) => (
                <div key={item.key} className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-3">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <p className="text-sm font-extrabold text-goodseed-950">{item.itemName}</p>
                      <p className="mt-1 text-xs font-bold text-goodseed-600">คงเหลือ {item.remaining.toLocaleString("th-TH")} {item.unit} • {item.warehouse}</p>
                    </div>
                    <MaterialStatusBadge status={item.status} />
                  </div>
                </div>
              ))}
              {lowStockRows.length + outStockRows.length === 0 && <p className="text-sm font-bold text-goodseed-700">ไม่มีรายการใกล้หมดหรือหมดสต็อก</p>}
              <div className="rounded-lg bg-amber-50 p-3 text-sm font-bold leading-6 text-amber-800">เตือน: ตรวจนับน้ำมันและอะไหล่ระบบน้ำทุกสิ้นวัน เพื่อป้องกันสต็อกไม่ตรงกับการใช้งานจริง</div>
            </div>
          </DashboardPanel>

          <DashboardPanel id="inventory-permission" title="Permission Levels">
            <div className="space-y-3 text-sm font-semibold leading-6 text-goodseed-700">
              <p><strong className="text-goodseed-950">Owner:</strong> ดู เพิ่ม แก้ไข ลบ และ Export ได้ทั้งหมด</p>
              <p><strong className="text-goodseed-950">Admin / Manager:</strong> เพิ่ม แก้ไข อนุมัติการเบิก และ Export ได้</p>
              <p><strong className="text-goodseed-950">Staff:</strong> เพิ่มรายการนำเข้า/เบิกใช้ได้ แต่แก้ไขย้อนหลังไม่ได้</p>
              <p><strong className="text-goodseed-950">Customer/Public:</strong> ไม่เห็นหน้านี้</p>
            </div>
          </DashboardPanel>

          <DashboardPanel id="inventory-smart-actions" title="Smart Features">
            <div className="grid gap-3">
              {[
                ["Search Materials", "ค้นหาวัสดุจากชื่อ หมวด รายละเอียด และผู้เกี่ยวข้อง"],
                ["Filter by Category", "กรองตามหมวดหมู่ วันที่ แปลง ผู้เบิก และสถานะ"],
                ["QR / Barcode Scan", "เตรียมเชื่อม QR Code และ Barcode Scan สำหรับคลัง"],
                ["Auto Remaining", "คำนวณคงเหลือจากนำเข้า - เบิกใช้"],
                ["Low Stock Warning", "แจ้งเตือนวัสดุใกล้หมดและหมดสต็อก"],
              ].map(([title, detail]) => (
                <div key={title} className="rounded-lg border border-goodseed-100 bg-white p-3 shadow-sm">
                  <p className="text-sm font-extrabold text-goodseed-950">{title}</p>
                  <p className="mt-1 text-xs font-semibold leading-5 text-goodseed-600">{detail}</p>
                </div>
              ))}
            </div>
          </DashboardPanel>

          <DashboardPanel id="inventory-report-center" title="Reports">
            <div className="grid gap-2">
              {["รายงานรายวัน", "รายงานรายสัปดาห์", "รายงานรายเดือน", "รายงานสต๊อกคงเหลือ", "ประวัติการนำเข้า/เบิกใช้", "รายงานซ่อมบำรุงอุปกรณ์"].map((report) => (
                <button key={report} onClick={canExport ? exportCsv : undefined} className="flex items-center justify-between rounded-lg border border-goodseed-100 bg-white px-3 py-3 text-sm font-extrabold text-goodseed-800 hover:bg-goodseed-50">
                  <span>{report}</span>
                  <Icon name="download" className="h-4 w-4" />
                </button>
              ))}
            </div>
          </DashboardPanel>
        </aside>
      </div>
    </section>
  );
}

function ExperimentRdPage({ rdExperiments, setRdExperiments, role = "owner" }) {
  const emptyForm = {
    name: "",
    category: "",
    varietyId: rdVarieties[0].id,
    methodId: rdMethods[0].id,
    startDate: "",
    plantCount: 0,
    zone: "",
    owner: "",
    status: "active",
    goal: "",
    latestResult: "",
    issue: "ไม่พบ",
  };
  const [formOpen, setFormOpen] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState(emptyForm);
  const [statusFilter, setStatusFilter] = useState("all");
  const [categoryFilter, setCategoryFilter] = useState("all");
  const summary = getRdSummary(rdExperiments);
  const categories = [...new Set(rdExperiments.map((item) => item.category))];
  const visibleExperiments = rdExperiments.filter((item) => {
    if (statusFilter !== "all" && item.status !== statusFilter) return false;
    if (categoryFilter !== "all" && item.category !== categoryFilter) return false;
    return true;
  });
  const latestActive = rdExperiments.find((item) => item.status === "active") || rdExperiments[0];
  const varietyName = (id) => rdVarieties.find((item) => item.id === id)?.name || "-";
  const methodName = (id) => rdMethods.find((item) => item.id === id)?.name || "-";
  const statusLabel = { active: "กำลังดำเนินการ", completed: "เสร็จสิ้น", archived: "Archived" };
  const openCreate = () => {
    setEditingId(null);
    setForm(emptyForm);
    setFormOpen(true);
  };
  const openEdit = (experiment) => {
    setEditingId(experiment.id);
    setForm(experiment);
    setFormOpen(true);
  };
  const saveExperiment = (event) => {
    event.preventDefault();
    const payload = { ...form, plantCount: Number(form.plantCount || 0) };
    if (editingId) {
      setRdExperiments((current) => current.map((item) => item.id === editingId ? { ...item, ...payload } : item));
    } else {
      setRdExperiments((current) => [{ ...payload, id: `exp-${Date.now()}` }, ...current]);
    }
    setFormOpen(false);
    setEditingId(null);
    setForm(emptyForm);
  };
  const archiveExperiment = (id) => {
    setRdExperiments((current) => current.map((item) => item.id === id ? { ...item, status: "archived" } : item));
  };
  const fieldClass = "rounded-lg border border-goodseed-100 bg-white px-3 py-2 text-sm font-bold text-goodseed-900 outline-none focus:border-goodseed-500";

  return (
    <section id="experiment-rd" className="space-y-5">
      <div className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
        <SectionHeader
          title="Experiment & R&D"
          subtitle="หน้าเต็มสำหรับบริหารงานทดลองของ GoodSeed Farm รองรับหลายชนิดการทดลอง เพิ่ม แก้ไข และซ่อนรายการได้โดยไม่ทำให้ Dashboard หลักรก"
          action={<button onClick={openCreate} className="inline-flex items-center gap-2 rounded-lg bg-goodseed-700 px-4 py-3 text-sm font-black text-white"><Icon name="plus" className="h-4 w-4" />เพิ่มการทดลอง</button>}
        />
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          <DashboardCard label="จำนวนการทดลองทั้งหมด" value={summary.total} unit="รายการ" icon="leaf" tone="bg-goodseed-100 text-goodseed-800" />
          <DashboardCard label="การทดลองที่กำลังดำเนินการ" value={summary.active} unit="รายการ" icon="check" tone="bg-blue-100 text-blue-700" />
          <DashboardCard label="ผลทดลองล่าสุด" value={latestActive?.latestResult || "-"} unit="" icon="file" tone="bg-emerald-100 text-emerald-800" />
          <DashboardCard label="ปัญหาที่พบ" value={summary.issues} unit="รายการ" icon="bell" tone={summary.issues ? "bg-red-100 text-red-700" : "bg-goodseed-100 text-goodseed-800"} />
        </div>
      </div>

      <CrudGovernanceBar role={role} moduleId="rd-experiment" title="R&D Experiment CRUD" />

      {formOpen && (
        <form onSubmit={saveExperiment} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft sm:p-6">
          <div className="mb-4 flex items-start justify-between gap-3">
            <div>
              <h3 className="text-lg font-black text-goodseed-950">{editingId ? "แก้ไขการทดลอง" : "เพิ่มการทดลองใหม่"}</h3>
              <p className="mt-1 text-sm font-bold text-goodseed-600">โครงสร้างนี้ตั้งไว้ให้ต่อยอดเป็น CRUD จริงหรือเชื่อมฐานข้อมูลได้ภายหลัง</p>
            </div>
            <button type="button" onClick={() => setFormOpen(false)} className="rounded-lg bg-goodseed-50 p-2 text-goodseed-800"><Icon name="x" /></button>
          </div>
          <div className="grid gap-3 md:grid-cols-2">
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">ชื่อการทดลอง<input required className={fieldClass} value={form.name} onChange={(event) => setForm({ ...form, name: event.target.value })} /></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">ประเภทการทดลอง<input required className={fieldClass} value={form.category} onChange={(event) => setForm({ ...form, category: event.target.value })} /></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">สายพันธุ์ / กลุ่มทดลอง<select className={fieldClass} value={form.varietyId} onChange={(event) => setForm({ ...form, varietyId: event.target.value })}>{rdVarieties.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">รูปแบบทดลอง<select className={fieldClass} value={form.methodId} onChange={(event) => setForm({ ...form, methodId: event.target.value })}>{rdMethods.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">วันที่เริ่ม<input className={fieldClass} value={form.startDate} onChange={(event) => setForm({ ...form, startDate: event.target.value })} /></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">จำนวนต้น/ชุด<input type="number" min="0" className={fieldClass} value={form.plantCount} onChange={(event) => setForm({ ...form, plantCount: event.target.value })} /></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">พื้นที่/โซน<input className={fieldClass} value={form.zone} onChange={(event) => setForm({ ...form, zone: event.target.value })} /></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">ผู้รับผิดชอบ<input className={fieldClass} value={form.owner} onChange={(event) => setForm({ ...form, owner: event.target.value })} /></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">สถานะ<select className={fieldClass} value={form.status} onChange={(event) => setForm({ ...form, status: event.target.value })}><option value="active">กำลังดำเนินการ</option><option value="completed">เสร็จสิ้น</option><option value="archived">Archived</option></select></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800">ผลทดลองล่าสุด<input className={fieldClass} value={form.latestResult} onChange={(event) => setForm({ ...form, latestResult: event.target.value })} /></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800 md:col-span-2">เป้าหมาย<textarea className={`${fieldClass} min-h-24`} value={form.goal} onChange={(event) => setForm({ ...form, goal: event.target.value })} /></label>
            <label className="grid gap-1 text-sm font-extrabold text-goodseed-800 md:col-span-2">ปัญหาที่พบ<textarea className={`${fieldClass} min-h-20`} value={form.issue} onChange={(event) => setForm({ ...form, issue: event.target.value })} /></label>
          </div>
          <div className="mt-4 flex flex-wrap justify-end gap-2">
            <button type="button" onClick={() => setFormOpen(false)} className="rounded-lg border border-goodseed-100 bg-white px-4 py-2 text-sm font-black text-goodseed-800">ยกเลิก</button>
            <button type="submit" className="rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-black text-white">บันทึก</button>
          </div>
        </form>
      )}

      <DashboardPanel
        title="รายการทดลองทั้งหมด"
        action={<div className="flex flex-wrap gap-2"><select className={fieldClass} value={categoryFilter} onChange={(event) => setCategoryFilter(event.target.value)}><option value="all">ทุกประเภท</option>{categories.map((item) => <option key={item} value={item}>{item}</option>)}</select><select className={fieldClass} value={statusFilter} onChange={(event) => setStatusFilter(event.target.value)}><option value="all">ทุกสถานะ</option><option value="active">กำลังดำเนินการ</option><option value="completed">เสร็จสิ้น</option><option value="archived">Archived</option></select></div>}
      >
        <div className="grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
          <div className="grid gap-3">
            {visibleExperiments.map((experiment) => (
              <article key={experiment.id} className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <p className="text-xs font-black text-goodseed-600">{experiment.category}</p>
                    <h3 className="mt-1 text-lg font-black leading-snug text-goodseed-950">{experiment.name}</h3>
                  </div>
                  <Badge className={experiment.status === "active" ? "bg-blue-100 text-blue-700 ring-blue-200" : experiment.status === "completed" ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : "bg-slate-100 text-slate-600 ring-slate-200"}>{statusLabel[experiment.status]}</Badge>
                </div>
                <p className="mt-3 text-sm font-semibold leading-6 text-goodseed-700">{experiment.goal}</p>
                <div className="mt-4 grid gap-2 text-xs font-bold text-goodseed-700 sm:grid-cols-2">
                  <span className="rounded-md bg-white p-2">สายพันธุ์: {varietyName(experiment.varietyId)}</span>
                  <span className="rounded-md bg-white p-2">วิธีทดลอง: {methodName(experiment.methodId)}</span>
                  <span className="rounded-md bg-white p-2">โซน: {experiment.zone}</span>
                  <span className="rounded-md bg-white p-2">ผู้รับผิดชอบ: {experiment.owner}</span>
                </div>
                <div className="mt-4 flex flex-wrap gap-2">
                  <button onClick={() => openEdit(experiment)} className="inline-flex items-center gap-2 rounded-lg bg-white px-3 py-2 text-xs font-black text-goodseed-800 ring-1 ring-goodseed-100"><Icon name="edit" className="h-4 w-4" />แก้ไข</button>
                  <button onClick={() => archiveExperiment(experiment.id)} className="inline-flex items-center gap-2 rounded-lg bg-red-50 px-3 py-2 text-xs font-black text-red-700 ring-1 ring-red-100"><Icon name="trash" className="h-4 w-4" />ลบ / ซ่อน</button>
                </div>
              </article>
            ))}
          </div>
          <div className="thin-scrollbar overflow-x-auto rounded-lg border border-goodseed-100">
            <table className="min-w-[900px] w-full text-left text-sm">
              <thead className="bg-goodseed-50 text-goodseed-800"><tr>{["ชื่อการทดลอง", "ประเภท", "รูปแบบ", "จำนวน", "ผลล่าสุด", "ปัญหา", "สถานะ"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr></thead>
              <tbody className="divide-y divide-goodseed-100 bg-white">
                {visibleExperiments.map((experiment) => (
                  <tr key={experiment.id}>
                    <td className="px-3 py-3 font-black text-goodseed-950">{experiment.name}</td>
                    <td className="px-3 py-3">{experiment.category}</td>
                    <td className="px-3 py-3">{methodName(experiment.methodId)}</td>
                    <td className="px-3 py-3">{experiment.plantCount}</td>
                    <td className="px-3 py-3">{experiment.latestResult}</td>
                    <td className="px-3 py-3">{experiment.issue}</td>
                    <td className="px-3 py-3"><StatusBadge status={experiment.status === "active" ? "กำลังทำ" : experiment.status === "completed" ? "เสร็จแล้ว" : "รอดำเนินการ"} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </DashboardPanel>
    </section>
  );
}

const documentCategories = ["ทั้งหมด", "SOP", "คู่มือการทำงาน", "แบบฟอร์ม", "Company Policy", "GAP", "Export Docs", "เอกสารอบรม", "เอกสาร HR", "เอกสารอุปกรณ์ / เครื่องจักร", "เอกสารอื่น ๆ"];
const documentFileTypes = ["ทั้งหมด", "PDF", "Word", "Excel", "PowerPoint", "Image", "Google Docs Link", "Google Sheets Link", "Google Forms Link", "Google Drive Link"];
const documentStatuses = ["ทั้งหมด", "Active", "Draft", "Archived", "Waiting for Approval", "Expired"];
const documentAccessLevels = ["ทั้งหมด", "Owner", "Admin", "Manager", "Staff", "Customer/Public"];
const farmDocumentsStorageKey = "goodseed-documents-center-records";
const farmDocumentsBucket = "goodseed-documents";

const farmDocuments = [
  { id: "DOC-001", name: "SOP การตรวจแปลงไม้ล้อมประจำวัน", category: "SOP", description: "ขั้นตอนตรวจแปลง ระบบน้ำ โรคแมลง วัชพืช และรูปภาพหลักฐาน", version: "v1.4", uploadDate: "25 พ.ค. 2569", uploader: "คุณหวาน", owner: "ผู้จัดการแปลง", size: "2.4 MB", status: "Active", downloads: 86, type: "PDF", access: "Staff", effectiveDate: "1 มิ.ย. 2569", expiryDate: "31 ธ.ค. 2569", lastUpdated: "25 พ.ค. 2569", canDelete: true },
  { id: "DOC-002", name: "แบบฟอร์มรายงานประจำวัน", category: "แบบฟอร์ม", description: "แบบฟอร์มตรวจงานประจำวันพร้อมแนบรูปและข้อมูล QR", version: "v2.1", uploadDate: "24 พ.ค. 2569", uploader: "Admin Farm", owner: "ฝ่ายปฏิบัติการ", size: "Google Form", status: "Active", downloads: 142, type: "Google Forms Link", access: "Staff", effectiveDate: "24 พ.ค. 2569", expiryDate: "-", lastUpdated: "24 พ.ค. 2569", canDelete: false },
  { id: "DOC-003", name: "คู่มือระบบน้ำและโครงข่ายกระจายน้ำ", category: "คู่มือการทำงาน", description: "คู่มือเปิดปิดน้ำ ตรวจแรงดัน และบันทึกปัญหาในพื้นที่รอบโครงข่ายกระจายน้ำภายในฟาร์ม", version: "v1.0", uploadDate: "23 พ.ค. 2569", uploader: "พี่ไกร", owner: "ทีมระบบน้ำ", size: "18 MB", status: "Waiting for Approval", downloads: 38, type: "PowerPoint", access: "Manager", effectiveDate: "1 มิ.ย. 2569", expiryDate: "-", lastUpdated: "23 พ.ค. 2569", canDelete: false },
  { id: "DOC-004", name: "Company Policy สวัสดิการและการลา", category: "Company Policy", description: "นโยบายวันลา OT ยูนิฟอร์ม โบนัส และสวัสดิการพนักงานฟาร์ม", version: "v1.2", uploadDate: "21 พ.ค. 2569", uploader: "น.ส.รุ่งนภา", owner: "People / HR", size: "1.1 MB", status: "Active", downloads: 74, type: "Word", access: "Staff", effectiveDate: "1 มิ.ย. 2569", expiryDate: "31 พ.ค. 2570", lastUpdated: "22 พ.ค. 2569", canDelete: true },
  { id: "DOC-005", name: "GAP Checklist เตรียมตรวจมาตรฐาน", category: "GAP", description: "รายการตรวจเอกสารและพื้นที่ก่อนยื่นขอมาตรฐาน GAP", version: "Draft 0.9", uploadDate: "20 พ.ค. 2569", uploader: "Admin Farm", owner: "ฝ่ายมาตรฐาน", size: "780 KB", status: "Draft", downloads: 22, type: "Excel", access: "Manager", effectiveDate: "15 มิ.ย. 2569", expiryDate: "-", lastUpdated: "20 พ.ค. 2569", canDelete: true },
  { id: "DOC-006", name: "Export Capability Profile", category: "Export Docs", description: "ข้อมูลศักยภาพฟาร์มสำหรับลูกค้า นักลงทุน คู่ค้า และตลาดส่งออก", version: "v1.0", uploadDate: "18 พ.ค. 2569", uploader: "Owner", owner: "Owner", size: "5.8 MB", status: "Active", downloads: 51, type: "PDF", access: "Owner", effectiveDate: "18 พ.ค. 2569", expiryDate: "-", lastUpdated: "18 พ.ค. 2569", canDelete: false },
  { id: "DOC-007", name: "คู่มือเครื่องตัดหญ้าและเครื่องพ่นยา", category: "เอกสารอุปกรณ์ / เครื่องจักร", description: "ขั้นตอนตรวจความพร้อม PM และข้อควรระวังในการใช้งาน", version: "v1.1", uploadDate: "15 พ.ค. 2569", uploader: "พี่สมชาย", owner: "Equipment & Vehicle", size: "8 รูป", status: "Active", downloads: 43, type: "Image", access: "Staff", effectiveDate: "15 พ.ค. 2569", expiryDate: "-", lastUpdated: "16 พ.ค. 2569", canDelete: true },
  { id: "DOC-008", name: "เอกสารอบรม QR Traceability", category: "เอกสารอบรม", description: "สไลด์อบรมการสแกน QR ต้นไม้ แปลง อุปกรณ์ รถ และวัสดุ", version: "v1.0", uploadDate: "12 พ.ค. 2569", uploader: "คุณหวาน", owner: "Training", size: "12.6 MB", status: "Active", downloads: 67, type: "PowerPoint", access: "Staff", effectiveDate: "12 พ.ค. 2569", expiryDate: "-", lastUpdated: "12 พ.ค. 2569", canDelete: true },
  { id: "DOC-009", name: "ทะเบียนเอกสาร HR 2569", category: "เอกสาร HR", description: "ทะเบียนเอกสารพนักงาน สิทธิ์สวัสดิการ และผู้ติดต่อฉุกเฉิน", version: "v1.0", uploadDate: "10 พ.ค. 2569", uploader: "น.ส.รุ่งนภา", owner: "People / HR", size: "Google Sheets", status: "Active", downloads: 18, type: "Google Sheets Link", access: "Admin", effectiveDate: "10 พ.ค. 2569", expiryDate: "-", lastUpdated: "25 พ.ค. 2569", canDelete: false },
  { id: "DOC-010", name: "เอกสารจัดซื้อวัสดุเดือนพฤษภาคม", category: "เอกสารอื่น ๆ", description: "ใบเสนอราคา ใบส่งของ และหลักฐานรับเข้าวัสดุ", version: "v1.0", uploadDate: "5 พ.ค. 2569", uploader: "Admin Farm", owner: "Inventory / Warehouse", size: "Google Drive", status: "Archived", downloads: 29, type: "Google Drive Link", access: "Manager", effectiveDate: "5 พ.ค. 2569", expiryDate: "-", lastUpdated: "8 พ.ค. 2569", canDelete: true },
  { id: "DOC-011", name: "ใบอนุญาตรถฟาร์มและประกัน", category: "เอกสารอุปกรณ์ / เครื่องจักร", description: "ทะเบียนรถ ประกัน และรอบต่ออายุเอกสารรถฟาร์ม", version: "v1.0", uploadDate: "1 พ.ค. 2569", uploader: "Admin Farm", owner: "Equipment & Vehicle", size: "3.2 MB", status: "Expired", downloads: 9, type: "PDF", access: "Admin", effectiveDate: "1 พ.ค. 2569", expiryDate: "28 พ.ค. 2569", lastUpdated: "1 พ.ค. 2569", canDelete: true },
];

const documentStatusClasses = {
  Active: "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  Draft: "bg-slate-100 text-slate-700 ring-slate-200",
  Archived: "bg-zinc-100 text-zinc-700 ring-zinc-200",
  "Waiting for Approval": "bg-amber-100 text-amber-800 ring-amber-200",
  Expired: "bg-red-100 text-red-700 ring-red-200",
};

const documentTypeTone = {
  PDF: "bg-red-50 text-red-700 ring-red-100",
  Word: "bg-blue-50 text-blue-700 ring-blue-100",
  Excel: "bg-goodseed-50 text-goodseed-800 ring-goodseed-100",
  PowerPoint: "bg-orange-50 text-orange-700 ring-orange-100",
  Image: "bg-purple-50 text-purple-700 ring-purple-100",
  "Google Docs Link": "bg-sky-50 text-sky-700 ring-sky-100",
  "Google Sheets Link": "bg-emerald-50 text-emerald-700 ring-emerald-100",
  "Google Forms Link": "bg-violet-50 text-violet-700 ring-violet-100",
  "Google Drive Link": "bg-yellow-50 text-yellow-800 ring-yellow-100",
};

function canEditDocument(role, doc) {
  return isOwnerRole(role) || role === "admin" || (role === "manager" && ["แบบฟอร์ม", "คู่มือการทำงาน", "เอกสารอบรม"].includes(doc.category));
}

function canDeleteDocument(role, doc) {
  return isOwnerRole(role) || (role === "admin" && doc.canDelete);
}

function canViewDocument(role, doc) {
  if (role === "customer") return doc.access === "Customer/Public";
  if (isOwnerRole(role) || role === "admin") return true;
  if (role === "manager") return ["Staff", "Manager", "Admin"].includes(doc.access);
  return doc.access === "Staff";
}

function readFarmDocuments() {
  return readLocalArray(farmDocumentsStorageKey, farmDocuments);
}

function writeFarmDocuments(documents) {
  writeLocalArray(farmDocumentsStorageKey, documents);
}

function thaiDateLabel(value) {
  if (!value) return "-";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);
  return date.toLocaleDateString("th-TH", { day: "numeric", month: "short", year: "numeric" });
}

function inputDateOrNull(value) {
  return value && value !== "-" ? value : null;
}

function inferDocumentTypeFromFile(file) {
  const extension = fileExtension(file?.name || "");
  if (extension === "pdf") return "PDF";
  if (["doc", "docx"].includes(extension)) return "Word";
  if (["xls", "xlsx", "csv"].includes(extension)) return "Excel";
  if (["ppt", "pptx"].includes(extension)) return "PowerPoint";
  if (["jpg", "jpeg", "png", "webp"].includes(extension)) return "Image";
  return "PDF";
}

function mapSupabaseDocument(row, files = []) {
  const totalSize = files.reduce((sum, file) => sum + (Number(file.file_size) || 0), 0);
  const firstFile = files[0];
  return {
    id: row.id,
    documentCode: row.document_code || row.id,
    name: row.name,
    category: row.category,
    description: row.description || "-",
    version: row.version || "v1.0",
    uploadDate: thaiDateLabel(row.created_at),
    uploader: row.uploader_name || "GoodSeed User",
    owner: row.owner_name || "-",
    size: files.length ? `${formatFileSize(totalSize)} / ${files.length} ไฟล์` : (row.google_link ? "Google Link" : "-"),
    status: row.status || "Waiting for Approval",
    downloads: row.downloads || 0,
    type: row.file_type || firstFile?.file_type || "PDF",
    access: row.access_level || "Staff",
    effectiveDate: row.effective_date ? thaiDateLabel(row.effective_date) : "-",
    expiryDate: row.expiry_date ? thaiDateLabel(row.expiry_date) : "-",
    lastUpdated: thaiDateLabel(row.updated_at || row.created_at),
    canDelete: row.can_delete !== false,
    files,
    link: row.google_link || "",
    storageStatus: "cloud",
  };
}

function documentDbPayload(form, userId, uploaderName, status = "Waiting for Approval") {
  return {
    name: form.name || "เอกสารใหม่",
    category: form.category,
    description: form.description || "-",
    version: form.version || "v1.0",
    owner_name: form.owner || uploaderName,
    access_level: form.access,
    file_type: form.type,
    status,
    effective_date: inputDateOrNull(form.effectiveDate),
    expiry_date: inputDateOrNull(form.expiryDate),
    google_link: form.link || null,
    uploaded_by: userId,
    uploader_name: uploaderName,
    can_delete: true,
  };
}

function DocumentTypeBadge({ type }) {
  const shortLabel = type.includes("Google") ? type.replace(" Link", "") : type;
  return <Badge className={documentTypeTone[type] || "bg-slate-100 text-slate-700 ring-slate-200"}>{shortLabel}</Badge>;
}

function documentOpenUrl(doc) {
  return doc?.files?.find((file) => file.signed_url)?.signed_url || doc?.link || "";
}

function DocumentCard({ doc, role, onPreview }) {
  const editable = canEditDocument(role, doc);
  const deletable = canDeleteDocument(role, doc);
  const openUrl = documentOpenUrl(doc);
  return (
    <article className="flex h-full flex-col rounded-xl border border-goodseed-100 bg-white p-4 shadow-soft">
      <div className="flex items-start justify-between gap-3">
        <div className="grid h-12 w-12 shrink-0 place-items-center rounded-xl bg-goodseed-50 text-goodseed-800 ring-1 ring-goodseed-100">
          <Icon name={doc.type === "Image" ? "camera" : doc.type.includes("Google") ? "qr" : "file"} />
        </div>
        <div className="flex flex-wrap justify-end gap-2">
          <DocumentTypeBadge type={doc.type} />
          <Badge className={documentStatusClasses[doc.status]}>{doc.status}</Badge>
        </div>
      </div>
      <div className="mt-4 flex-1">
        <p className="text-xs font-extrabold uppercase tracking-wide text-goodseed-500">{doc.category}</p>
        <h3 className="mt-1 text-lg font-extrabold leading-snug text-goodseed-950">{doc.name}</h3>
        <p className="mt-2 text-sm font-semibold leading-7 text-goodseed-700">{doc.description}</p>
        <div className="mt-4 grid grid-cols-2 gap-2 text-xs font-bold text-goodseed-700">
          <span>เวอร์ชัน: {doc.version}</span>
          <span>ขนาด: {doc.size}</span>
          <span>อัปโหลด: {doc.uploadDate}</span>
          <span>ดาวน์โหลด: {doc.downloads}</span>
          <span>โดย: {doc.uploader}</span>
          <span>สิทธิ์: {doc.access}</span>
        </div>
      </div>
      <div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
        <button onClick={() => onPreview(doc)} className="rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white">Preview</button>
        <button onClick={() => openUrl ? window.open(openUrl, "_blank", "noopener,noreferrer") : downloadFile(`${doc.name}.txt`, `GOODSEED Farm Document\n${doc.name}\n${doc.description}`, "text/plain;charset=utf-8")} className="rounded-lg border border-goodseed-200 px-3 py-2 text-xs font-extrabold text-goodseed-800">Download</button>
        <button disabled={!editable} className={`rounded-lg border px-3 py-2 text-xs font-extrabold ${editable ? "border-goodseed-200 text-goodseed-800" : "border-slate-100 text-slate-300"}`}>Edit</button>
        <button disabled={!deletable} className={`rounded-lg border px-3 py-2 text-xs font-extrabold ${deletable ? "border-red-200 text-red-700" : "border-slate-100 text-slate-300"}`}>Delete</button>
      </div>
    </article>
  );
}

function UploadDocumentPanel({ open, onClose, role, authProfile, onSave }) {
  const [form, setForm] = useState({
    name: "SOP การตรวจแปลงรอบใหม่",
    category: "SOP",
    version: "v1.0",
    effectiveDate: "2026-06-01",
    expiryDate: "",
    owner: "คุณหวาน",
    access: "Staff",
    type: "PDF",
    description: "ขั้นตอนตรวจแปลงและบันทึกรายงานสำหรับผู้จัดการแปลง",
    link: "",
  });
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [saveMessage, setSaveMessage] = useState("");
  const [saving, setSaving] = useState(false);
  const canUpload = ["owner", "admin", "manager"].includes(role);
  const documentAcceptTypes = ".pdf,.doc,.docx,.xls,.xlsx,.csv,.ppt,.pptx,image/*";
  const updateUploadForm = (patch) => setForm((current) => ({ ...current, ...patch }));
  const handleDocumentFiles = (fileList) => {
    if (!canUpload) return;
    setSelectedFiles(Array.from(fileList || []));
    setSaveMessage("");
  };
  const saveDocumentDraft = async () => {
    if (!canUpload) return;
    setSaving(true);
    setSaveMessage("");
    const fileText = selectedFiles.length ? `${selectedFiles.length} ไฟล์` : "ยังไม่ได้เลือกไฟล์";
    const totalSize = selectedFiles.reduce((sum, file) => sum + file.size, 0);
    const inferredType = selectedFiles[0] ? inferDocumentTypeFromFile(selectedFiles[0]) : form.type;
    const savedDoc = {
      id: `DOC-UP-${Date.now()}`,
      name: form.name || selectedFiles[0]?.name || "เอกสารใหม่",
      category: form.category,
      description: form.description || "-",
      version: form.version || "v1.0",
      uploadDate: new Date().toLocaleDateString("th-TH", { day: "numeric", month: "short", year: "numeric" }),
      uploader: authProfile?.fullName || authProfile?.full_name || authProfile?.email || roleInfo(role).label,
      owner: form.owner || authProfile?.fullName || authProfile?.full_name || roleInfo(role).label,
      size: selectedFiles.length ? `${(totalSize / 1024 / 1024).toFixed(2)} MB / ${selectedFiles.length} ไฟล์` : (form.link ? "Google Link" : "-"),
      status: "Waiting for Approval",
      downloads: 0,
      type: inferredType || form.type,
      access: form.access,
      effectiveDate: form.effectiveDate || "-",
      expiryDate: form.expiryDate || "-",
      lastUpdated: new Date().toLocaleDateString("th-TH", { day: "numeric", month: "short", year: "numeric" }),
      canDelete: true,
      files: selectedFiles.map((file) => ({ name: file.name, size: file.size, type: file.type })),
      link: form.link,
    };
    try {
      await onSave?.(savedDoc, selectedFiles, { ...form, type: savedDoc.type });
      setSaveMessage(`บันทึก "${savedDoc.name}" (${savedDoc.type}) พร้อม ${fileText} แล้ว`);
      setSelectedFiles([]);
      window.setTimeout(onClose, 650);
    } catch (error) {
      setSaveMessage(`บันทึกไม่สำเร็จ: ${supabaseAuthMessage(error)}`);
    } finally {
      setSaving(false);
    }
  };
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[80] bg-goodseed-950/45 p-3 backdrop-blur-sm">
      <div className="ml-auto flex h-full max-w-2xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
        <div className="flex items-start justify-between gap-4 border-b border-goodseed-100 p-5">
          <div>
            <h3 className="text-xl font-extrabold text-goodseed-950">Upload Document</h3>
            <p className="mt-1 text-sm font-semibold text-goodseed-700">อัปโหลดเอกสาร แนบไฟล์ หรือแนบลิงก์ Google Drive / Docs / Sheets / Forms</p>
          </div>
          <button onClick={onClose} className="rounded-lg border border-goodseed-100 p-2 text-goodseed-800"><Icon name="x" /></button>
        </div>
        <div className="thin-scrollbar flex-1 overflow-y-auto p-5">
          {!canUpload && <div className="mb-4 rounded-lg bg-amber-50 p-4 text-sm font-bold text-amber-800">Role นี้ดูและดาวน์โหลดเอกสารได้ แต่ยังไม่มีสิทธิ์ Upload Document</div>}
          <div className="grid gap-4 sm:grid-cols-2">
            <Input label="ชื่อเอกสาร" value={form.name} onChange={(value) => updateUploadForm({ name: value })} />
            <Select label="หมวดหมู่เอกสาร" value={form.category} onChange={(value) => updateUploadForm({ category: value })} options={documentCategories.filter((item) => item !== "ทั้งหมด")} />
            <Input label="เวอร์ชัน" value={form.version} onChange={(value) => updateUploadForm({ version: value })} />
            <Input label="วันที่มีผลบังคับใช้" type="date" value={form.effectiveDate} onChange={(value) => updateUploadForm({ effectiveDate: value })} />
            <Input label="วันหมดอายุ ถ้ามี" type="date" value={form.expiryDate} onChange={(value) => updateUploadForm({ expiryDate: value })} />
            <Input label="ผู้รับผิดชอบเอกสาร" value={form.owner} onChange={(value) => updateUploadForm({ owner: value })} />
            <Select label="สิทธิ์การเข้าถึง" value={form.access} onChange={(value) => updateUploadForm({ access: value })} options={["Owner", "Admin", "Manager", "Staff", "Customer/Public"]} />
            <Select label="ประเภทไฟล์" value={form.type} onChange={(value) => updateUploadForm({ type: value })} options={documentFileTypes.filter((item) => item !== "ทั้งหมด")} />
          </div>
          <label className="mt-4 block text-sm font-bold text-goodseed-800">คำอธิบาย<textarea rows="3" value={form.description} onChange={(event) => updateUploadForm({ description: event.target.value })} className="mt-2 w-full rounded-lg border border-goodseed-100 px-3 py-2 text-sm outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" /></label>
          <div
            className="mt-4 rounded-xl border-2 border-dashed border-goodseed-200 bg-goodseed-50 p-6 text-center"
            onDragOver={(event) => event.preventDefault()}
            onDrop={(event) => {
              event.preventDefault();
              handleDocumentFiles(event.dataTransfer.files);
            }}
          >
            <Icon name="upload" className="mx-auto h-10 w-10 text-goodseed-700" />
            <p className="mt-3 text-sm font-extrabold text-goodseed-900">Drag & Drop files here</p>
            <p className="mt-1 text-xs font-bold text-goodseed-600">รองรับหลายไฟล์: PDF, Word, Excel, PowerPoint, Image</p>
            <input
              id="goodseed-document-upload-input"
              type="file"
              multiple
              accept={documentAcceptTypes}
              disabled={!canUpload}
              onChange={(event) => handleDocumentFiles(event.target.files)}
              className="sr-only"
            />
            <label htmlFor="goodseed-document-upload-input" className={`mt-4 inline-flex cursor-pointer rounded-lg px-4 py-2 text-sm font-extrabold ${canUpload ? "bg-goodseed-700 text-white hover:bg-goodseed-800" : "pointer-events-none bg-slate-100 text-slate-400"}`}>
              เลือกไฟล์
            </label>
            <div className="mt-4 grid gap-2 text-left">
              {selectedFiles.length > 0 ? selectedFiles.map((file) => (
                <div key={`${file.name}-${file.size}`} className="flex items-center justify-between gap-3 rounded-lg bg-white px-3 py-2 text-xs font-bold text-goodseed-800 ring-1 ring-goodseed-100">
                  <span className="truncate">{file.name}</span>
                  <span className="shrink-0 text-goodseed-600">{(file.size / 1024 / 1024).toFixed(2)} MB</span>
                </div>
              )) : <p className="text-center text-xs font-bold text-goodseed-600">ยังไม่ได้เลือกไฟล์</p>}
            </div>
          </div>
          <Input label="แนบลิงก์ Google Drive / Docs / Sheets / Forms" value={form.link} onChange={(value) => updateUploadForm({ link: value })} />
          <div className="mt-4 space-y-3">
            <div className="flex items-center justify-between text-xs font-bold text-goodseed-700"><span>Upload Progress</span><span>{saving ? "กำลังบันทึก Cloud" : selectedFiles.length || form.link ? "พร้อมบันทึก" : "0%"}</span></div>
            <div className="h-2 rounded-full bg-goodseed-50"><div className="h-full rounded-full bg-goodseed-600" style={{ width: saving ? "65%" : selectedFiles.length || form.link ? "100%" : "0%" }} /></div>
            <div className="rounded-lg bg-goodseed-50 p-3 text-xs font-bold text-goodseed-800">
              {selectedFiles.length ? `เลือกแล้ว ${selectedFiles.length} ไฟล์: ${selectedFiles.map((file) => file.name).join(", ")}` : "Preview หลังอัปโหลดจะแสดงชื่อไฟล์ที่เลือกก่อนบันทึก"}
            </div>
            {saveMessage && <div className="rounded-lg bg-goodseed-100 p-3 text-xs font-bold text-goodseed-900">{saveMessage}</div>}
          </div>
        </div>
        <div className="flex justify-end gap-2 border-t border-goodseed-100 p-5">
          <button type="button" onClick={onClose} className="rounded-lg border border-goodseed-200 px-4 py-2 text-sm font-extrabold text-goodseed-800">ยกเลิก</button>
          <button type="button" onClick={saveDocumentDraft} disabled={!canUpload || saving} className={`rounded-lg px-4 py-2 text-sm font-extrabold ${canUpload && !saving ? "bg-goodseed-700 text-white" : "bg-slate-100 text-slate-400"}`}>{saving ? "กำลังบันทึก..." : "บันทึกเอกสาร"}</button>
        </div>
      </div>
    </div>
  );
}

function DocumentPreviewModal({ doc, onClose }) {
  if (!doc) return null;
  const openUrl = documentOpenUrl(doc);
  return (
    <div className="fixed inset-0 z-[90] grid place-items-center bg-goodseed-950/50 p-4 backdrop-blur-sm">
      <div className="w-full max-w-3xl overflow-hidden rounded-2xl bg-white shadow-2xl">
        <div className="flex items-start justify-between gap-4 border-b border-goodseed-100 p-5">
          <div>
            <h3 className="text-xl font-extrabold text-goodseed-950">{doc.name}</h3>
            <p className="mt-1 text-sm font-semibold text-goodseed-700">{doc.category} / {doc.type} / {doc.version}</p>
          </div>
          <button onClick={onClose} className="rounded-lg border border-goodseed-100 p-2 text-goodseed-800"><Icon name="x" /></button>
        </div>
        <div className="p-5">
          <div className="grid min-h-[260px] place-items-center rounded-xl border border-goodseed-100 bg-goodseed-50 text-center">
            <div>
              <Icon name={doc.type === "Image" ? "camera" : "file"} className="mx-auto h-14 w-14 text-goodseed-700" />
              <p className="mt-4 text-lg font-extrabold text-goodseed-950">Document Preview</p>
              <p className="mt-2 max-w-lg text-sm font-semibold leading-7 text-goodseed-700">{doc.description}</p>
              {openUrl && <button type="button" onClick={() => window.open(openUrl, "_blank", "noopener,noreferrer")} className="mt-4 rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white">เปิดไฟล์ / ลิงก์</button>}
            </div>
          </div>
          {doc.files?.length > 0 && (
            <div className="mt-4 rounded-xl border border-goodseed-100 bg-white p-3">
              <p className="text-sm font-black text-goodseed-950">ไฟล์ที่เก็บใน Cloud</p>
              <div className="mt-2 grid gap-2">
                {doc.files.map((file) => (
                  <button key={file.id || file.storage_path || file.file_name} type="button" onClick={() => file.signed_url && window.open(file.signed_url, "_blank", "noopener,noreferrer")} className="flex items-center justify-between gap-3 rounded-lg bg-goodseed-50 px-3 py-2 text-left text-xs font-bold text-goodseed-800">
                    <span className="truncate">{file.file_name || file.name}</span>
                    <span className="shrink-0">{formatFileSize(file.file_size || file.size)}</span>
                  </button>
                ))}
              </div>
            </div>
          )}
          <div className="mt-4 grid gap-3 sm:grid-cols-3">
            <MiniMetric label="สถานะ" value={doc.status} danger={doc.status === "Expired"} />
            <MiniMetric label="ผู้รับผิดชอบ" value={doc.owner} />
            <MiniMetric label="หมดอายุ" value={doc.expiryDate} danger={doc.status === "Expired"} />
          </div>
        </div>
      </div>
    </div>
  );
}

const dailyWorkOrderStorageKey = "goodseed-daily-work-orders";
const dailyWorkTypeOptions = ["งานปลูก", "งานบำรุงรักษา", "งานระบบน้ำ", "งานก่อสร้าง", "งานซ่อมแซม", "งานขนส่ง", "งานจัดซื้อ / จัดเตรียม", "งานเก็บเกี่ยว", "งานกำจัดวัชพืช", "งานพ่นสาร", "งานตัดแต่ง / ล้อมต้นไม้", "งานทำความสะอาด", "งานทั่วไป"];
const dailyEmploymentOptions = ["รายวัน", "รายชั่วโมง", "เหมางาน", "ตามผลงาน", "ผู้รับเหมา"];
const dailySopOptions = ["ได้รับคำอธิบายงานแล้ว", "ตรวจสอบพื้นที่ / อุปกรณ์พร้อมใช้งาน", "สวมใส่ PPE ครบถ้วน", "ปฏิบัติตามขั้นตอน SOP", "ทำงานด้วยความปลอดภัย", "ทำงานเสร็จตามเป้าหมาย", "ตรวจสอบความเรียบร้อยของงาน", "ถ่ายภาพหลังเสร็จงาน", "ส่งมอบงานให้ผู้ตรวจรับ"];

function createEmptyDailyWorkOrder(authProfile) {
  const today = todayInputValue();
  const name = authProfile?.fullName || authProfile?.full_name || authProfile?.email || "";
  return {
    work_order_no: `DWO-${today.replaceAll("-", "")}-${String(Date.now()).slice(-4)}`,
    work_date: today,
    project_name: "",
    job_detail: "",
    location_area: "",
    start_date: today,
    start_time: "08:00",
    end_date: today,
    end_time: "17:00",
    work_types: [],
    work_type_other: "",
    employment_types: ["รายวัน"],
    employment_type_other: "",
    workers: Array.from({ length: 10 }, (_, index) => ({ no: index + 1, name: index === 0 ? name : "", phone: "", type: "", wage: "", signature: "" })),
    sop_checklist: [],
    proof_note: "",
    inspection_result: "draft",
    inspection_detail: "",
    inspector_name: "",
    payment_details: { daily_rate: "", daily_qty: "", daily_amount: "", hourly_rate: "", hourly_qty: "", hourly_amount: "", lump_sum: "", piece_rate: "", piece_qty: "", piece_amount: "", other_expenses: "", total_amount: "" },
    payment_method: "เงินสด",
    paid_at: today,
    payer_name: "",
    status: "draft",
  };
}

function toggleValue(list, value) {
  return list.includes(value) ? list.filter((item) => item !== value) : [...list, value];
}

function DailyWorkOrderModal({ open, onClose, role = "staff", authProfile, onSaved }) {
  const [form, setForm] = useState(() => createEmptyDailyWorkOrder(authProfile));
  const [photos, setPhotos] = useState([]);
  const [savedOrders, setSavedOrders] = useState([]);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState("");
  const localKey = `${dailyWorkOrderStorageKey}:${authProfile?.id || authProfile?.email || role}`;

  useEffect(() => {
    if (!open) return;
    try {
      setSavedOrders(JSON.parse(window.localStorage?.getItem(localKey) || "[]"));
    } catch (error) {
      setSavedOrders([]);
    }
  }, [open, localKey]);

  const update = (key, value) => setForm((current) => ({ ...current, [key]: value }));
  const updateWorker = (index, key, value) => setForm((current) => ({ ...current, workers: current.workers.map((worker, workerIndex) => workerIndex === index ? { ...worker, [key]: value } : worker) }));
  const updatePayment = (key, value) => setForm((current) => ({ ...current, payment_details: { ...current.payment_details, [key]: value } }));

  const storeLocal = (record) => {
    const next = [{ ...record, saved_at: new Date().toISOString(), photo_names: photos.map((file) => file.name) }, ...savedOrders.filter((item) => item.id !== record.id)].slice(0, 50);
    window.localStorage?.setItem(localKey, JSON.stringify(next));
    setSavedOrders(next);
  };

  const savePhotos = async (client, workOrderId, userId) => {
    for (const file of photos) {
      const storagePath = `${userId}/${workOrderId}/${Date.now()}-${safeStorageName(file.name)}`;
      const { error: uploadError } = await client.storage.from("daily-work-order-photos").upload(storagePath, file, { upsert: false, contentType: file.type || "application/octet-stream" });
      if (uploadError) throw uploadError;
      const { error: photoError } = await client.from("daily_work_order_photos").insert({
        work_order_id: workOrderId,
        file_name: file.name,
        file_type: file.type,
        file_size: file.size,
        storage_path: storagePath,
        uploaded_by: userId,
      });
      if (photoError) throw photoError;
    }
  };

  const saveOrder = async (nextStatus = "draft") => {
    setSaving(true);
    setNotice("");
    const payload = { ...form, status: nextStatus };
    try {
      const client = getSupabaseClient({ silent: true });
      const { data: userData } = client ? await client.auth.getUser() : { data: null };
      const userId = userData?.user?.id || authProfile?.id;
      if (!client || !userId) throw new Error("missing-supabase-session");
      const dbPayload = {
        ...payload,
        id: payload.id || undefined,
        created_by: payload.created_by || userId,
        updated_by: userId,
      };
      const { data, error } = await client.from("daily_work_orders").upsert(dbPayload).select("*").single();
      if (error) throw error;
      if (photos.length) await savePhotos(client, data.id, userId);
      setForm((current) => ({ ...current, ...data }));
      setPhotos([]);
      setNotice(nextStatus === "submitted" ? "บันทึกและ Submit ใบงานเข้าระบบแล้ว" : "บันทึก Draft ลง Supabase แล้ว");
      onSaved?.(`บันทึกใบว่าจ้างงานรายวัน ${data.work_order_no || data.id} เรียบร้อยแล้ว`);
    } catch (error) {
      const localRecord = { ...payload, id: payload.id || `local-${Date.now()}` };
      storeLocal(localRecord);
      setNotice(`บันทึกสำรองในเครื่องนี้แล้ว แต่ยังไม่เข้า Supabase: ${supabaseAuthMessage(error)}`);
      onSaved?.("บันทึกใบว่าจ้างงานรายวันสำรองในเครื่องนี้แล้ว กรุณารัน SQL และสร้าง Storage bucket เพื่อบันทึกถาวร");
    } finally {
      setSaving(false);
    }
  };

  const exportCsv = () => {
    const rows = [
      ["เลขที่เอกสาร", form.work_order_no],
      ["วันที่", form.work_date],
      ["ชื่อโครงการ / งาน", form.project_name],
      ["รายละเอียดงาน", form.job_detail],
      ["สถานที่", form.location_area],
      ["ประเภทงาน", form.work_types.join(" / ")],
      ["รูปแบบการจ้าง", form.employment_types.join(" / ")],
      ["ผลตรวจรับ", form.inspection_result],
      ["รวมเงิน", form.payment_details.total_amount],
      ["ผู้จ่ายเงิน", form.payer_name],
      [],
      ["ลำดับ", "ชื่อ-สกุล", "โทรศัพท์", "รูปแบบ", "ค่าจ้าง", "ลายมือชื่อ"],
      ...form.workers.filter((worker) => worker.name || worker.phone || worker.wage).map((worker) => [worker.no, worker.name, worker.phone, worker.type, worker.wage, worker.signature]),
    ];
    downloadFile(`daily-work-order-${form.work_date}.csv`, `\ufeff${rows.map((row) => row.map(csvEscape).join(",")).join("\n")}`, "text/csv;charset=utf-8");
  };

  const printOrder = () => {
    const html = `<!doctype html><html lang="th"><meta charset="utf-8"><title>${form.work_order_no}</title><style>body{font-family:Tahoma,Arial,sans-serif;padding:24px;color:#111}h1{color:#075f19}.box{border:1px solid #9aa59a;border-radius:8px;padding:12px;margin:10px 0}table{width:100%;border-collapse:collapse}td,th{border:1px solid #aaa;padding:6px;text-align:left}th{background:#eef5ee}@media print{button{display:none}}</style><body><button onclick="window.print()">Print</button><h1>ใบว่าจ้างงานรายวัน GoodSeed Farm</h1><div class="box"><b>เลขที่:</b> ${form.work_order_no} <b>วันที่:</b> ${form.work_date}<br><b>งาน:</b> ${form.project_name}<br><b>รายละเอียด:</b> ${form.job_detail}<br><b>สถานที่:</b> ${form.location_area}</div><div class="box"><b>ประเภทงาน:</b> ${form.work_types.join(", ")} ${form.work_type_other}<br><b>รูปแบบจ้าง:</b> ${form.employment_types.join(", ")} ${form.employment_type_other}</div><table><thead><tr><th>ลำดับ</th><th>ชื่อ</th><th>โทร</th><th>รูปแบบ</th><th>ค่าจ้าง</th><th>ลายมือชื่อ</th></tr></thead><tbody>${form.workers.map((worker) => `<tr><td>${worker.no}</td><td>${worker.name || ""}</td><td>${worker.phone || ""}</td><td>${worker.type || ""}</td><td>${worker.wage || ""}</td><td>${worker.signature || ""}</td></tr>`).join("")}</tbody></table><div class="box"><b>SOP:</b> ${form.sop_checklist.join(", ") || "-"}<br><b>ผลตรวจรับ:</b> ${form.inspection_result}<br>${form.inspection_detail || ""}</div><div class="box"><b>รวมเงิน:</b> ${form.payment_details.total_amount || "-"} บาท<br><b>วิธีจ่าย:</b> ${form.payment_method}<br><b>ผู้จ่าย:</b> ${form.payer_name || "-"}</div></body></html>`;
    const win = window.open("", "_blank");
    win.document.write(html);
    win.document.close();
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[90] bg-goodseed-950/50 p-3 backdrop-blur-sm">
      <div className="mx-auto flex h-full max-w-7xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
        <div className="flex flex-col gap-3 border-b border-goodseed-100 p-5 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-sm font-extrabold text-goodseed-700">Documents Center / Daily Work Order</p>
            <h3 className="text-2xl font-black text-goodseed-950">ใบว่าจ้างงานรายวัน</h3>
            <p className="mt-1 text-sm font-semibold text-goodseed-700">กรอกงานรายวัน แนบรูป บันทึกเป็นหลักฐาน พิมพ์ หรือดาวน์โหลดไฟล์</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <button type="button" onClick={printOrder} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800"><Icon name="file" className="h-4 w-4" />พิมพ์</button>
            <button type="button" onClick={exportCsv} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800"><Icon name="download" className="h-4 w-4" />CSV</button>
            <button type="button" onClick={() => downloadFile(`daily-work-order-${form.work_date}.json`, JSON.stringify({ ...form, photos: photos.map((file) => ({ name: file.name, size: file.size, type: file.type })) }, null, 2), "application/json;charset=utf-8")} className="inline-flex items-center gap-2 rounded-lg border border-goodseed-200 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800"><Icon name="download" className="h-4 w-4" />JSON</button>
            <button type="button" disabled={saving} onClick={() => saveOrder("draft")} className="inline-flex items-center gap-2 rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white disabled:opacity-60"><Icon name="save" className="h-4 w-4" />บันทึก Draft</button>
            <button type="button" disabled={saving} onClick={() => saveOrder("submitted")} className="inline-flex items-center gap-2 rounded-lg bg-goodseed-900 px-4 py-2 text-sm font-extrabold text-white disabled:opacity-60"><Icon name="check" className="h-4 w-4" />Submit</button>
            <button type="button" onClick={onClose} className="rounded-lg border border-goodseed-100 p-2 text-goodseed-800"><Icon name="x" /></button>
          </div>
        </div>
        <div className="thin-scrollbar flex-1 overflow-y-auto p-5">
          {notice && <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-bold text-amber-800">{notice}</div>}
          <div className="grid gap-4 lg:grid-cols-4">
            <Input label="เลขที่เอกสาร" value={form.work_order_no} onChange={(value) => update("work_order_no", value)} />
            <Input label="วันที่" type="date" value={form.work_date} onChange={(value) => update("work_date", value)} />
            <Input label="วันที่เริ่มงาน" type="date" value={form.start_date} onChange={(value) => update("start_date", value)} />
            <Input label="เวลาเริ่ม" type="time" value={form.start_time} onChange={(value) => update("start_time", value)} />
            <Input label="ชื่อโครงการ / งาน" value={form.project_name} onChange={(value) => update("project_name", value)} />
            <Input label="สถานที่ / พื้นที่ปฏิบัติงาน" value={form.location_area} onChange={(value) => update("location_area", value)} />
            <Input label="วันที่เสร็จงาน" type="date" value={form.end_date} onChange={(value) => update("end_date", value)} />
            <Input label="เวลาสิ้นสุด" type="time" value={form.end_time} onChange={(value) => update("end_time", value)} />
          </div>
          <div className="mt-4"><Textarea label="รายละเอียดงานโดยย่อ" value={form.job_detail} onChange={(value) => update("job_detail", value)} /></div>
          <div className="mt-5 grid gap-4 lg:grid-cols-2">
            <div className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
              <h4 className="font-black text-goodseed-950">ประเภทงาน</h4>
              <div className="mt-3 grid gap-2 sm:grid-cols-2">{dailyWorkTypeOptions.map((item) => <label key={item} className="flex items-center gap-2 rounded-lg bg-white px-3 py-2 text-sm font-bold text-goodseed-800 ring-1 ring-goodseed-100"><input type="checkbox" checked={form.work_types.includes(item)} onChange={() => update("work_types", toggleValue(form.work_types, item))} className="h-4 w-4 accent-goodseed-700" />{item}</label>)}</div>
              <Input label="อื่นๆ" value={form.work_type_other} onChange={(value) => update("work_type_other", value)} />
            </div>
            <div className="rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
              <h4 className="font-black text-goodseed-950">รูปแบบการจ้างงาน</h4>
              <div className="mt-3 grid gap-2 sm:grid-cols-2">{dailyEmploymentOptions.map((item) => <label key={item} className="flex items-center gap-2 rounded-lg bg-white px-3 py-2 text-sm font-bold text-goodseed-800 ring-1 ring-goodseed-100"><input type="checkbox" checked={form.employment_types.includes(item)} onChange={() => update("employment_types", toggleValue(form.employment_types, item))} className="h-4 w-4 accent-goodseed-700" />{item}</label>)}</div>
              <Input label="อื่นๆ" value={form.employment_type_other} onChange={(value) => update("employment_type_other", value)} />
            </div>
          </div>
          <div className="mt-5 rounded-lg border border-goodseed-100 bg-white p-4">
            <h4 className="font-black text-goodseed-950">รายละเอียดผู้ปฏิบัติงาน</h4>
            <div className="thin-scrollbar mt-3 overflow-x-auto">
              <table className="min-w-[980px] w-full text-left text-sm">
                <thead className="bg-goodseed-50 text-goodseed-800"><tr>{["ลำดับ", "ชื่อ-สกุล", "เบอร์โทร", "รูปแบบ", "ค่าจ้าง", "ลายมือชื่อ"].map((head) => <th key={head} className="px-3 py-2 font-extrabold">{head}</th>)}</tr></thead>
                <tbody className="divide-y divide-goodseed-100">{form.workers.map((worker, index) => <tr key={worker.no}><td className="px-3 py-2 font-black">{worker.no}</td>{["name", "phone", "type", "wage", "signature"].map((key) => <td key={key} className="px-3 py-2"><input value={worker[key]} onChange={(event) => updateWorker(index, key, event.target.value)} className="w-full rounded-lg border border-goodseed-100 px-3 py-2 font-semibold outline-none focus:border-goodseed-500" /></td>)}</tr>)}</tbody>
              </table>
            </div>
          </div>
          <div className="mt-5 rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
            <h4 className="font-black text-goodseed-950">SOP Checklist</h4>
            <div className="mt-3 grid gap-2 md:grid-cols-3">{dailySopOptions.map((item) => <label key={item} className="flex items-center gap-2 rounded-lg bg-white px-3 py-2 text-sm font-bold text-goodseed-800 ring-1 ring-goodseed-100"><input type="checkbox" checked={form.sop_checklist.includes(item)} onChange={() => update("sop_checklist", toggleValue(form.sop_checklist, item))} className="h-4 w-4 accent-goodseed-700" />{item}</label>)}</div>
          </div>
          <div className="mt-5 grid gap-4 lg:grid-cols-2">
            <div className="rounded-lg border border-goodseed-100 bg-white p-4">
              <h4 className="font-black text-goodseed-950">หลักฐานประกอบงาน / รูปถ่าย</h4>
              <input type="file" multiple accept="image/*" onChange={(event) => setPhotos(Array.from(event.target.files || []))} className="mt-3 block w-full rounded-lg border border-goodseed-100 p-3 text-sm font-bold text-goodseed-800" />
              <div className="mt-3 grid gap-2">{photos.length ? photos.map((file) => <div key={`${file.name}-${file.size}`} className="rounded-lg bg-goodseed-50 px-3 py-2 text-xs font-bold text-goodseed-800">{file.name} / {formatFileSize(file.size)}</div>) : <p className="text-sm font-bold text-goodseed-600">ยังไม่ได้เลือกรูป</p>}</div>
              <Textarea label="หมายเหตุหลักฐาน" value={form.proof_note} onChange={(value) => update("proof_note", value)} />
            </div>
            <div className="rounded-lg border border-goodseed-100 bg-white p-4">
              <h4 className="font-black text-goodseed-950">ผลการตรวจรับงาน</h4>
              <Select label="ผลตรวจรับ" value={form.inspection_result} onChange={(value) => update("inspection_result", value)} options={["draft", "ผ่าน", "ผ่าน มีเงื่อนไข", "ไม่ผ่าน"]} />
              <Textarea label="รายละเอียด / เหตุผล" value={form.inspection_detail} onChange={(value) => update("inspection_detail", value)} />
              <Input label="ผู้ตรวจรับงาน" value={form.inspector_name} onChange={(value) => update("inspector_name", value)} />
            </div>
          </div>
          <div className="mt-5 rounded-lg border border-goodseed-100 bg-white p-4">
            <h4 className="font-black text-goodseed-950">รายละเอียดการจ่ายเงิน</h4>
            <div className="mt-3 grid gap-3 lg:grid-cols-4">{[
              ["daily_rate", "ค่าแรงรายวัน / วัน"], ["daily_qty", "จำนวนวัน"], ["daily_amount", "รวมรายวัน"], ["hourly_rate", "ค่าแรงรายชั่วโมง"], ["hourly_qty", "จำนวนชั่วโมง"], ["hourly_amount", "รวมรายชั่วโมง"], ["lump_sum", "เหมางาน"], ["piece_rate", "ค่าผลงาน / หน่วย"], ["piece_qty", "จำนวนหน่วย"], ["piece_amount", "รวมค่าผลงาน"], ["other_expenses", "ค่าใช้จ่ายอื่นๆ"], ["total_amount", "รวมเป็นเงินทั้งสิ้น"],
            ].map(([key, label]) => <Input key={key} label={label} value={form.payment_details[key] || ""} onChange={(value) => updatePayment(key, value)} />)}
              <Select label="วิธีการจ่ายเงิน" value={form.payment_method} onChange={(value) => update("payment_method", value)} options={["เงินสด", "โอนเงิน", "อื่นๆ"]} />
              <Input label="วันที่จ่ายเงิน" type="date" value={form.paid_at} onChange={(value) => update("paid_at", value)} />
              <Input label="ผู้จ่ายเงิน" value={form.payer_name} onChange={(value) => update("payer_name", value)} />
            </div>
          </div>
          <div className="mt-5 rounded-lg border border-goodseed-100 bg-goodseed-50 p-4">
            <h4 className="font-black text-goodseed-950">รายการที่บันทึกในเครื่องนี้ชั่วคราว</h4>
            <div className="mt-3 grid gap-2">{savedOrders.length ? savedOrders.slice(0, 8).map((order) => <button key={order.id} type="button" onClick={() => setForm({ ...createEmptyDailyWorkOrder(authProfile), ...order })} className="rounded-lg bg-white px-3 py-2 text-left text-sm font-bold text-goodseed-800 ring-1 ring-goodseed-100">{order.work_order_no || order.id} / {order.work_date} / {order.project_name || "-"}</button>) : <p className="text-sm font-bold text-goodseed-600">ยังไม่มีรายการสำรองในเครื่อง</p>}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function DocumentsCenterPage({ role, authProfile }) {
  const [documents, setDocuments] = useState(readFarmDocuments);
  const [documentNotice, setDocumentNotice] = useState("");
  const [documentStorageMode, setDocumentStorageMode] = useState("local");
  const [query, setQuery] = useState("");
  const [category, setCategory] = useState("ทั้งหมด");
  const [fileType, setFileType] = useState("ทั้งหมด");
  const [status, setStatus] = useState("ทั้งหมด");
  const [access, setAccess] = useState("ทั้งหมด");
  const [sortBy, setSortBy] = useState("อัปเดตล่าสุด");
  const [view, setView] = useState("card");
  const [uploadOpen, setUploadOpen] = useState(false);
  const [workOrderOpen, setWorkOrderOpen] = useState(false);
  const [previewDoc, setPreviewDoc] = useState(null);
  const canUpload = ["owner", "admin", "manager"].includes(role);
  const loadCloudDocuments = async () => {
    const client = getSupabaseClient({ silent: true });
    if (!client) {
      setDocumentStorageMode("local");
      return;
    }
    try {
      const { data, error } = await client
        .from("farm_documents")
        .select("*, farm_document_files(*)")
        .order("updated_at", { ascending: false });
      if (error) throw error;
      const cloudDocs = await Promise.all((data || []).map(async (row) => {
        const rawFiles = row.farm_document_files || [];
        const files = await Promise.all(rawFiles.map(async (file) => {
          const { data: signed } = await client.storage.from(file.storage_bucket || farmDocumentsBucket).createSignedUrl(file.storage_path, 60 * 60);
          return { ...file, signed_url: signed?.signedUrl || "" };
        }));
        return mapSupabaseDocument(row, files);
      }));
      if (cloudDocs.length) {
        setDocuments(cloudDocs);
        writeFarmDocuments(cloudDocs);
      }
      setDocumentStorageMode("cloud");
    } catch (error) {
      console.warn("GoodSeed documents cloud load failed", error);
      setDocumentStorageMode("local");
      setDocumentNotice(`ยังโหลดศูนย์เอกสารจาก Supabase ไม่ได้ จึงใช้รายการในเครื่องก่อน: ${supabaseAuthMessage(error)} กรุณารัน supabase/documents_center.sql`);
    }
  };

  useEffect(() => {
    loadCloudDocuments();
  }, [authProfile?.id, role]);

  const addDocumentToState = (doc) => {
    setDocuments((current) => {
      const nextDocuments = [doc, ...current];
      writeFarmDocuments(nextDocuments);
      return nextDocuments;
    });
  };

  const saveUploadedDocument = async (doc, files = [], rawForm = {}) => {
    const client = getSupabaseClient({ silent: true });
    try {
      const { data: userData } = client ? await client.auth.getUser() : { data: null };
      const userId = userData?.user?.id || authProfile?.id;
      if (!client || !userId) throw new Error("missing-supabase-session");
      const uploaderName = authProfile?.fullName || authProfile?.full_name || authProfile?.email || roleInfo(role).label;
      const { data: insertedDoc, error: docError } = await client
        .from("farm_documents")
        .insert(documentDbPayload(rawForm, userId, uploaderName))
        .select("*")
        .single();
      if (docError) throw docError;
      const cloudFiles = [];
      for (const file of files) {
        const storagePath = `${userId}/${insertedDoc.id}/${Date.now()}-${safeStorageName(file.name)}`;
        const { error: uploadError } = await client.storage.from(farmDocumentsBucket).upload(storagePath, file, {
          cacheControl: "3600",
          contentType: file.type || "application/octet-stream",
          upsert: false,
        });
        if (uploadError) throw uploadError;
        const { data: fileRow, error: fileError } = await client.from("farm_document_files").insert({
          document_id: insertedDoc.id,
          file_name: file.name,
          file_type: file.type || fileExtension(file.name),
          file_size: file.size,
          storage_bucket: farmDocumentsBucket,
          storage_path: storagePath,
          uploaded_by: userId,
        }).select("*").single();
        if (fileError) throw fileError;
        const { data: signed } = await client.storage.from(farmDocumentsBucket).createSignedUrl(storagePath, 60 * 60);
        cloudFiles.push({ ...fileRow, signed_url: signed?.signedUrl || "" });
      }
      const cloudDoc = mapSupabaseDocument(insertedDoc, cloudFiles);
      addDocumentToState(cloudDoc);
      setDocumentStorageMode("cloud");
      setDocumentNotice(`บันทึกเอกสาร "${cloudDoc.name}" ลง Supabase Storage แล้ว`);
      setUploadOpen(false);
    } catch (error) {
      const fallbackDoc = { ...doc, storageStatus: "local-backup", localError: supabaseAuthMessage(error) };
      addDocumentToState(fallbackDoc);
      setDocumentStorageMode("local");
      setDocumentNotice(`บันทึกเอกสาร "${doc.name}" สำรองในเครื่องแล้ว แต่ยังไม่เข้า Cloud: ${supabaseAuthMessage(error)} กรุณารัน supabase/documents_center.sql`);
      setUploadOpen(false);
    }
  };
  const visibleDocs = documents
    .filter((doc) => canViewDocument(role, doc))
    .filter((doc) => category === "ทั้งหมด" || doc.category === category)
    .filter((doc) => fileType === "ทั้งหมด" || doc.type === fileType)
    .filter((doc) => status === "ทั้งหมด" || doc.status === status)
    .filter((doc) => access === "ทั้งหมด" || doc.access === access)
    .filter((doc) => {
      const text = `${doc.name} ${doc.description} ${doc.category} ${doc.owner} ${doc.uploader}`.toLowerCase();
      return text.includes(query.toLowerCase());
    })
    .sort((a, b) => sortBy === "ดาวน์โหลดมากที่สุด" ? b.downloads - a.downloads : sortBy === "วันที่อัปโหลด" ? b.id.localeCompare(a.id) : b.lastUpdated.localeCompare(a.lastUpdated));
  const expiringDocs = documents.filter((doc) => ["Expired", "Waiting for Approval"].includes(doc.status));

  return (
    <section id="documents-center" className="space-y-5">
      <DashboardPanel
        title={<BiLabel th="Documents Center" en="ศูนย์รวมเอกสาร แบบฟอร์ม และคู่มือการทำงานของ GOODSEED Farm" />}
        action={<div className="flex flex-wrap gap-2"><button onClick={() => setWorkOrderOpen(true)} className="inline-flex items-center gap-2 rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white shadow-sm"><Icon name="edit" className="h-4 w-4" />ใบว่าจ้างงานรายวัน</button><button onClick={() => setUploadOpen(true)} className={`inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-extrabold shadow-sm ${canUpload ? "bg-white text-goodseed-800 ring-1 ring-goodseed-100" : "bg-slate-100 text-slate-500"}`}><Icon name="upload" className="h-4 w-4" />Upload Document</button></div>}
      >
        <div className="grid gap-3 md:grid-cols-4">
          <MiniMetric label="เอกสารที่มองเห็น" value={`${visibleDocs.length} ไฟล์`} />
          <MiniMetric label="Active" value={`${visibleDocs.filter((doc) => doc.status === "Active").length} ไฟล์`} />
          <MiniMetric label="Waiting Approval" value={`${visibleDocs.filter((doc) => doc.status === "Waiting for Approval").length} ไฟล์`} danger />
          <MiniMetric label={documentStorageMode === "cloud" ? "Cloud Storage" : "Local Backup"} value={documentStorageMode === "cloud" ? "Supabase" : "ในเครื่อง"} danger={documentStorageMode !== "cloud"} />
        </div>
        <div className="mt-5 grid gap-3 lg:grid-cols-[1.5fr_repeat(5,1fr)]">
          <label className="relative">
            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-goodseed-400"><Icon name="file" className="h-4 w-4" /></span>
            <input value={query} onChange={(event) => setQuery(event.target.value)} className="w-full rounded-lg border border-goodseed-100 bg-white py-3 pl-10 pr-4 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="ค้นหาชื่อเอกสาร คำอธิบาย หมวดหมู่ ผู้รับผิดชอบ..." />
          </label>
          <Select label="หมวดหมู่" value={category} onChange={setCategory} options={documentCategories} />
          <Select label="ประเภทไฟล์" value={fileType} onChange={setFileType} options={documentFileTypes} />
          <Select label="สถานะ" value={status} onChange={setStatus} options={documentStatuses} />
          <Select label="สิทธิ์เข้าถึง" value={access} onChange={setAccess} options={documentAccessLevels} />
          <Select label="Sort" value={sortBy} onChange={setSortBy} options={["อัปเดตล่าสุด", "วันที่อัปโหลด", "ดาวน์โหลดมากที่สุด"]} />
        </div>
        <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
          <div className="flex flex-wrap gap-2">
            {["PDF", "Word", "Excel", "PowerPoint", "Image", "Google Drive Link"].map((type) => <button key={type} onClick={() => setFileType(type)} className="rounded-lg bg-goodseed-50 px-3 py-2 text-xs font-extrabold text-goodseed-800 ring-1 ring-goodseed-100">{type}</button>)}
          </div>
          <div className="rounded-lg border border-goodseed-100 bg-white p-1 shadow-sm">
            {["card", "table"].map((mode) => <button key={mode} onClick={() => setView(mode)} className={`rounded-md px-3 py-2 text-xs font-extrabold ${view === mode ? "bg-goodseed-700 text-white" : "text-goodseed-800"}`}>{mode === "card" ? "Card Grid" : "Table View"}</button>)}
          </div>
        </div>
      </DashboardPanel>

      {documentNotice && (
        <div className="flex items-start justify-between gap-3 rounded-lg border border-goodseed-200 bg-goodseed-50 px-4 py-3 text-sm font-bold text-goodseed-800 shadow-soft">
          <span>{documentNotice}</span>
          <button type="button" onClick={() => setDocumentNotice("")} className="rounded-full p-1 text-goodseed-700 hover:bg-goodseed-100"><Icon name="x" className="h-4 w-4" /></button>
        </div>
      )}

      {view === "card" ? (
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {visibleDocs.map((doc) => <DocumentCard key={doc.id} doc={doc} role={role} onPreview={setPreviewDoc} />)}
        </div>
      ) : (
        <DashboardPanel title="Document Table View">
          <div className="thin-scrollbar overflow-x-auto">
            <table className="min-w-[1100px] w-full text-left text-sm">
              <thead className="bg-goodseed-50 text-goodseed-800">
                <tr>{["ชื่อเอกสาร", "หมวดหมู่", "ไฟล์", "เวอร์ชัน", "วันที่อัปโหลด", "ผู้อัปโหลด", "สถานะ", "ดาวน์โหลด", "Action"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}</tr>
              </thead>
              <tbody className="divide-y divide-goodseed-100">
                {visibleDocs.map((doc) => (
                  <tr key={doc.id} className="align-top">
                    <td className="px-3 py-3"><p className="font-extrabold text-goodseed-950">{doc.name}</p><p className="mt-1 text-xs font-semibold text-goodseed-600">{doc.description}</p></td>
                    <td className="px-3 py-3 font-bold text-goodseed-800">{doc.category}</td>
                    <td className="px-3 py-3"><DocumentTypeBadge type={doc.type} /></td>
                    <td className="px-3 py-3 font-bold">{doc.version}</td>
                    <td className="px-3 py-3 font-bold">{doc.uploadDate}</td>
                    <td className="px-3 py-3 font-bold">{doc.uploader}</td>
                    <td className="px-3 py-3"><Badge className={documentStatusClasses[doc.status]}>{doc.status}</Badge></td>
                    <td className="px-3 py-3 font-extrabold">{doc.downloads}</td>
                    <td className="px-3 py-3"><button onClick={() => setPreviewDoc(doc)} className="rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white">Preview</button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </DashboardPanel>
      )}

      <div className="grid gap-5 xl:grid-cols-3">
        <DashboardPanel title="Version Control">
          <div className="space-y-3">
            {visibleDocs.slice(0, 4).map((doc) => <div key={doc.id} className="rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800">{doc.name}: {doc.version} / อัปเดตล่าสุด {doc.lastUpdated}</div>)}
          </div>
        </DashboardPanel>
        <DashboardPanel title="Expiry Alert & Approval Flow">
          <div className="space-y-3">
            {expiringDocs.map((doc) => <div key={doc.id} className="rounded-lg bg-amber-50 p-3 text-sm font-bold text-amber-800">{doc.status}: {doc.name} / หมดอายุ {doc.expiryDate}</div>)}
          </div>
        </DashboardPanel>
        <DashboardPanel title="Download Log / Activity Log">
          <div className="space-y-3">
            {["คุณหวานดาวน์โหลด SOP การตรวจแปลง เวลา 08:45 น.", "Admin Farm อัปโหลด GAP Checklist เวลา 10:20 น.", "น.ส.รุ่งนภาแก้ไข Policy สวัสดิการ เวลา 13:05 น.", "Owner Preview Export Capability Profile เวลา 14:10 น."].map((item) => <div key={item} className="rounded-lg bg-goodseed-50 p-3 text-sm font-bold text-goodseed-800">{item}</div>)}
          </div>
        </DashboardPanel>
      </div>

      <UploadDocumentPanel open={uploadOpen} onClose={() => setUploadOpen(false)} role={role} authProfile={authProfile} onSave={saveUploadedDocument} />
      <DailyWorkOrderModal open={workOrderOpen} onClose={() => setWorkOrderOpen(false)} role={role} authProfile={authProfile} onSaved={setDocumentNotice} />
      <DocumentPreviewModal doc={previewDoc} onClose={() => setPreviewDoc(null)} />
    </section>
  );
}

function NotificationCenterPage({ reports = initialReports, tasks = initialTasks, rdExperiments = initialRdExperiments, role = "owner" }) {
  const activity = buildTopbarActivityCenter({ reports, tasks, rdExperiments, role, readIds: [], selectedDate: todayInputValue() });
  return (
    <InternalModulePage
      title="Notification Center"
      subtitle="รวมแจ้งเตือนจากงาน ปฏิทิน รายงาน คลังสินค้า Tree Inspection, R&D และ Analytics / BI"
      icon="bell"
      cards={[
        { label: "ยังไม่อ่าน", value: activity.unreadNotifications, title: "รายการที่ต้องตรวจ" },
        { label: "เร่งด่วน", value: activity.notifications.filter((item) => item.priority === "High").length, title: "ต้องดำเนินการวันนี้" },
        { label: "รายงานใหม่", value: activity.unreadDocuments, title: "รอตรวจสอบ" },
      ]}
    >
      <div className="grid gap-3 lg:grid-cols-2">
        {activity.notifications.map((item) => (
          <a key={item.id} href={`#${item.route}`} className="rounded-lg border border-goodseed-100 bg-white p-4 shadow-soft transition hover:-translate-y-0.5 hover:shadow-lg">
            <div className="flex items-start gap-3">
              <div className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-goodseed-50 text-goodseed-800"><Icon name={notificationTypeIcon(item.type)} /></div>
              <div>
                <div className="flex flex-wrap gap-2"><Badge className={priorityTone(item.priority)}>{item.priority}</Badge><Badge className="bg-white text-goodseed-700 ring-goodseed-100">{item.type}</Badge></div>
                <p className="mt-2 font-extrabold text-goodseed-950">{item.title}</p>
                <p className="mt-1 text-sm font-semibold text-goodseed-700">{item.detail}</p>
              </div>
            </div>
          </a>
        ))}
      </div>
    </InternalModulePage>
  );
}

const analyticsNumber = (value, fallback = 0) => {
  const number = Number(value);
  return Number.isFinite(number) ? number : fallback;
};

const analyticsAverage = (rows, key, fallback = 0) => {
  const values = rows.map((row) => analyticsNumber(row[key], NaN)).filter((value) => Number.isFinite(value));
  return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : fallback;
};

const analyticsPercentFromText = (text, fallback = 0) => {
  const match = String(text || "").match(/([+-]?\d+(?:\.\d+)?)\s*%/);
  return match ? Number(match[1]) : fallback;
};

function AnalyticsBiPage({ reports = initialReports, tasks = initialTasks, rdExperiments = initialRdExperiments, role = "owner" }) {
  const plannerStore = readFarmPlanningTasks();
  const plannerTasks = Object.entries(plannerStore).flatMap(([planKey, rows]) => (rows || []).map((task) => ({ ...task, planKey })));
  const isStaff = role === "staff";
  const scopedReports = isStaff ? reports.filter((report) => report.reporter === "คุณหวาน" || report.owner === "คุณหวาน").slice(0, 6) : reports;
  const latestDate = scopedReports[0]?.date || new Date().toISOString().slice(0, 10);
  const todayReports = scopedReports.filter((report) => report.date === latestDate);
  const totalNormal = scopedReports.reduce((sum, report) => sum + analyticsNumber(report.normal), 0);
  const totalAbnormal = scopedReports.reduce((sum, report) => sum + analyticsNumber(report.abnormal), 0);
  const totalTrees = totalNormal + totalAbnormal;
  const treesPlanted = todayReports.reduce((sum, report) => sum + analyticsNumber(report.treesPlanted), 0);
  const rowsInspected = todayReports.reduce((sum, report) => sum + analyticsNumber(report.rowsInspected), 0);
  const laborCount = todayReports.reduce((sum, report) => sum + analyticsNumber(report.laborCount), 0);
  const materialQty = todayReports.reduce((sum, report) => sum + analyticsNumber(report.materialQty), 0);
  const dailyCost = todayReports.reduce((sum, report) => sum + analyticsNumber(report.dailyCost), 0);
  const completedToday = todayReports.filter((report) => report.workStatus === "Done").length + tasks.filter((task) => task.status === "เสร็จแล้ว").length + plannerTasks.filter((task) => task.status === "Done").length;
  const pendingTasks = tasks.filter((task) => task.status !== "เสร็จแล้ว").length + plannerTasks.filter((task) => task.status !== "Done").length;
  const productivity = laborCount ? treesPlanted / laborCount : 0;
  const survivalRate = scopedReports.length ? analyticsAverage(scopedReports, "survivalRate", totalTrees ? (totalNormal / totalTrees) * 100 : 0) : 0;
  const growthRate = scopedReports.length ? analyticsAverage(scopedReports, "growthRate", analyticsPercentFromText(scopedReports[0]?.experiment, 0)) : 0;
  const progressPercent = scopedReports.length ? analyticsAverage(scopedReports, "progressPercent", 0) : 0;
  const problemCount = totalAbnormal + scopedReports.filter((report) => [report.issue, report.disease, report.qrIssue, report.fieldWeatherNote].some((text) => String(text || "").includes("พบ") || String(text || "").includes("ผิดปกติ") || String(text || "").includes("น้ำขัง"))).length;
  const riskyReports = scopedReports.filter((report) => analyticsNumber(report.abnormal) > 15 || /เพลี้ย|ใบเหลือง|น้ำขัง|ชื้นเกิน|ผิดปกติ/.test(`${report.issue} ${report.disease} ${report.qrIssue} ${report.standingWater}`));
  const repeatedIssuePlots = Object.entries(riskyReports.reduce((map, report) => ({ ...map, [report.plotId || report.area]: (map[report.plotId || report.area] || 0) + 1 }), {})).filter(([, count]) => count > 1);
  const lowProductivity = productivity > 0 && productivity < 50;
  const alertsBi = [
    totalTrees && (totalAbnormal / totalTrees) * 100 > 1.5 ? `Tree Health: ต้นไม้ผิดปกติ ${totalAbnormal.toLocaleString("th-TH")} ต้น สูงกว่าเกณฑ์ 1.5%` : null,
    repeatedIssuePlots.length ? `Risk Heatmap: พบปัญหาซ้ำใน ${repeatedIssuePlots.map(([plot]) => plot).join(", ")}` : null,
    materialQty > 15 ? `Inventory Usage: ใช้วัสดุ ${materialQty.toLocaleString("th-TH")} หน่วย สูงกว่าค่าเฉลี่ย` : null,
    lowProductivity ? `Productivity: เฉลี่ย ${productivity.toFixed(1)} ต้น/คน/วัน ต่ำกว่าเป้าหมาย 50` : null,
    progressPercent < 75 ? `Work Progress: งานคืบหน้าเฉลี่ย ${progressPercent.toFixed(0)}% ต่ำกว่าแผน` : null,
    riskyReports.some((report) => /น้ำขัง|งดน้ำ|ระบบน้ำ|ชื้นเกิน/.test(`${report.water} ${report.standingWater} ${report.fieldWeatherNote}`)) ? "Field Condition: พบความเสี่ยงเรื่องระบบน้ำหรือความชื้นในแปลง" : null,
  ].filter(Boolean);
  const topKpis = [
    { label: "งานเสร็จวันนี้", value: completedToday.toLocaleString("th-TH"), unit: "งาน", hint: `ข้อมูลวันที่ ${latestDate}`, icon: "check", tone: "bg-goodseed-100 text-goodseed-800" },
    { label: "Productivity เฉลี่ย", value: productivity.toFixed(1), unit: "ต้น/คน/วัน", hint: `${treesPlanted.toLocaleString("th-TH")} ต้น / ${laborCount || 0} คน`, icon: "users", danger: lowProductivity, tone: "bg-sky-100 text-sky-800" },
    { label: "ต้นทุนวันนี้", value: dailyCost.toLocaleString("th-TH"), unit: "บาท", hint: `${rowsInspected || 1} แถว | ${treesPlanted || 1} ต้น`, icon: "money", tone: "bg-amber-100 text-amber-900" },
    { label: "จำนวนปัญหา", value: problemCount.toLocaleString("th-TH"), unit: "รายการ", hint: "รวมต้นผิดปกติและปัญหาภาคสนาม", icon: "bell", danger: problemCount > 20, tone: "bg-red-100 text-red-700" },
    { label: "อัตรารอด", value: survivalRate.toFixed(1), unit: "%", hint: `${totalNormal.toLocaleString("th-TH")} ปกติ / ${totalTrees.toLocaleString("th-TH")} รวม`, icon: "leaf", tone: "bg-goodseed-100 text-goodseed-800" },
    { label: "Growth Rate", value: growthRate.toFixed(1), unit: "%", hint: "เฉลี่ยจากรายงานและ R&D", icon: "tree", tone: "bg-lime-100 text-lime-800" },
    { label: "แปลงเสี่ยง", value: new Set(riskyReports.map((report) => report.plotId || report.area)).size.toLocaleString("th-TH"), unit: "แปลง", hint: "จากโรค แมลง น้ำ และต้นผิดปกติ", icon: "map", danger: riskyReports.length > 0, tone: "bg-orange-100 text-orange-800" },
    { label: "งานค้าง", value: pendingTasks.toLocaleString("th-TH"), unit: "งาน", hint: "รวม Responsibility และ Farm Work Planning", icon: "calendar", danger: pendingTasks > 5, tone: "bg-slate-100 text-slate-700" },
  ];
  const productivityRows = scopedReports.map((report) => ({
    label: report.plotId || report.area,
    value: analyticsNumber(report.laborCount) ? analyticsNumber(report.treesPlanted) / analyticsNumber(report.laborCount) : analyticsNumber(report.progressPercent, 0),
    note: `${report.workType || "Daily Report"} | ${report.reporter}`,
  }));
  const materialRows = Object.values(scopedReports.reduce((map, report) => {
    const key = report.materialUsed || "ไม่ระบุวัสดุ";
    const current = map[key] || { label: key, value: 0, cost: 0 };
    return { ...map, [key]: { ...current, value: current.value + analyticsNumber(report.materialQty), cost: current.cost + analyticsNumber(report.dailyCost) } };
  }, {}));
  const riskRows = scopedReports.map((report) => {
    const score = Math.min(100, Math.round((analyticsNumber(report.abnormal) / Math.max(1, analyticsNumber(report.normal) + analyticsNumber(report.abnormal))) * 1000) + (/เพลี้ย|ใบเหลือง|น้ำขัง|ชื้นเกิน/.test(`${report.issue} ${report.qrIssue} ${report.standingWater}`) ? 28 : 8));
    return { plot: report.plotId || report.area, row: report.rowId || report.plotZone, score, issue: report.issue || report.qrIssue || "ปกติ" };
  });
  const workStatusRows = [
    { label: "Done", value: tasks.filter((task) => task.status === "เสร็จแล้ว").length + plannerTasks.filter((task) => task.status === "Done").length },
    { label: "In Progress", value: tasks.filter((task) => task.status === "กำลังทำ").length + plannerTasks.filter((task) => task.status === "In Progress").length },
    { label: "Pending", value: tasks.filter((task) => task.status === "รอดำเนินการ").length + plannerTasks.filter((task) => task.status === "Pending").length },
  ];
  const rdActive = rdExperiments.filter((item) => item.status === "active").length;
  const insight = `วันนี้ปลูกได้ ${treesPlanted.toLocaleString("th-TH")} ต้น ใช้แรงงาน ${laborCount || 0} คน เฉลี่ย ${productivity.toFixed(1)} ต้น/คน/วัน ตรวจแล้ว ${rowsInspected.toLocaleString("th-TH")} แถว พบปัญหา ${problemCount.toLocaleString("th-TH")} รายการ ${riskyReports[0] ? `จุดที่ควรติดตามคือ ${riskyReports[0].plotId || riskyReports[0].area} / ${riskyReports[0].rowId || riskyReports[0].plotZone} (${riskyReports[0].issue || riskyReports[0].qrIssue})` : "ภาพรวมยังอยู่ในเกณฑ์ควบคุม"} แนะนำให้ตรวจระบบน้ำ ความชื้น และบันทึกรูปหลักฐานในรอบถัดไป`;
  const maxProductivity = Math.max(100, ...productivityRows.map((row) => row.value));
  const maxMaterial = Math.max(1, ...materialRows.map((row) => row.value));
  const maxStatus = Math.max(1, ...workStatusRows.map((row) => row.value));
  const costPerTree = treesPlanted ? dailyCost / treesPlanted : 0;
  const costPerRow = rowsInspected ? dailyCost / rowsInspected : 0;

  return (
    <section id="analytics-bi" className="space-y-5">
      <div className="rounded-lg border border-goodseed-100 bg-white p-5 shadow-soft sm:p-6">
        <SectionHeader title="Analytics / BI" subtitle="ศูนย์วิเคราะห์ข้อมูลจาก Daily Report, Tree Inspection, Inventory, Farm Work Planning, Experiment & R&D, HR, Cost และ Weather / Field Condition" />
        <div className="mt-4 flex flex-wrap gap-2">
          <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">Auto KPI Engine</Badge>
          <Badge className="bg-sky-100 text-sky-800 ring-sky-200">Daily Report Workspace</Badge>
          {isStaff && <Badge className="bg-amber-100 text-amber-900 ring-amber-200">Staff View: เห็นเฉพาะข้อมูลที่เกี่ยวข้อง</Badge>}
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {topKpis.map((card) => <KpiCard key={card.label} {...card} />)}
      </div>

      <DashboardPanel
        id="analytics-ai-insight"
        title="AI Insight Summary / สรุปวิเคราะห์อัตโนมัติ"
        action={<Badge className="bg-goodseed-700 text-white ring-goodseed-700">Forecast / Prediction Ready</Badge>}
      >
        <div className="grid gap-4 lg:grid-cols-[1.3fr_0.7fr]">
          <div className="rounded-lg bg-goodseed-950 p-5 text-white">
            <p className="text-sm font-extrabold uppercase tracking-[0.18em] text-goodseed-100">Insight</p>
            <p className="mt-3 text-lg font-bold leading-relaxed">{insight}</p>
          </div>
          <div className="rounded-lg border border-amber-100 bg-amber-50 p-4">
            <h4 className="font-extrabold text-amber-950">Auto Alerts / แจ้งเตือนผิดปกติ</h4>
            <div className="mt-3 space-y-2">
              {(alertsBi.length ? alertsBi : ["ยังไม่พบความผิดปกติระดับเร่งด่วน"]).map((alert) => (
                <div key={alert} className="rounded-lg bg-white px-3 py-2 text-sm font-bold text-amber-900 ring-1 ring-amber-100">{alert}</div>
              ))}
            </div>
          </div>
        </div>
      </DashboardPanel>

      <div className="grid gap-5 xl:grid-cols-2">
        <DashboardPanel id="analytics-productivity" title="Productivity Chart / ประสิทธิภาพต่อคนต่อวัน">
          <div className="space-y-4">
            {productivityRows.map((row) => (
              <AnalyticsBar key={`${row.label}-${row.note}`} label={row.label} value={row.value} max={maxProductivity} suffix="ต้น/คน" note={row.note} />
            ))}
          </div>
        </DashboardPanel>

        <DashboardPanel id="analytics-cost" title="Cost Analysis / วิเคราะห์ต้นทุน">
          <div className="grid gap-3 sm:grid-cols-3">
            <MiniMetric label="ต้นทุนรวมวันนี้" value={`${dailyCost.toLocaleString("th-TH")} บาท`} />
            <MiniMetric label="ต้นทุนต่อแถว" value={`${costPerRow.toFixed(0)} บาท`} />
            <MiniMetric label="ต้นทุนต่อต้น" value={`${costPerTree.toFixed(0)} บาท`} />
          </div>
          <div className="mt-4 space-y-3">
            {materialRows.map((row) => <AnalyticsBar key={row.label} label={row.label} value={row.value} max={maxMaterial} suffix="หน่วย" note={`${row.cost.toLocaleString("th-TH")} บาท`} />)}
          </div>
        </DashboardPanel>

        <DashboardPanel id="analytics-growth" title="Growth Rate Chart / Growth + Survival">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="rounded-lg bg-goodseed-50 p-4">
              <p className="text-sm font-extrabold text-goodseed-700">Growth Rate เฉลี่ย</p>
              <p className="mt-2 text-4xl font-extrabold text-goodseed-950">{growthRate.toFixed(1)}%</p>
              <MiniProgress value={Math.min(100, Math.max(0, growthRate * 10))} />
            </div>
            <div className="rounded-lg bg-goodseed-50 p-4">
              <p className="text-sm font-extrabold text-goodseed-700">Survival Rate</p>
              <p className="mt-2 text-4xl font-extrabold text-goodseed-950">{survivalRate.toFixed(1)}%</p>
              <MiniProgress value={Math.min(100, survivalRate)} />
            </div>
          </div>
          <div className="mt-4 rounded-lg border border-goodseed-100 p-4">
            <p className="font-extrabold text-goodseed-950">Experiment & R&D</p>
            <p className="mt-2 text-sm font-bold text-goodseed-700">กำลังดำเนินการ {rdActive} ชุดทดลอง ใช้เชื่อม Forecast การเจริญเติบโตและสูตรวัสดุปลูก</p>
          </div>
        </DashboardPanel>

        <DashboardPanel id="analytics-health" title="Tree Health Dashboard / สุขภาพต้นไม้">
          <div className="grid gap-4 sm:grid-cols-[180px_1fr]">
            <div className="grid h-44 w-44 place-items-center rounded-full" style={{ background: `conic-gradient(#2f8f46 0 ${survivalRate}%, #ef4444 ${survivalRate}% 100%)` }}>
              <div className="grid h-28 w-28 place-items-center rounded-full bg-white text-center shadow-inner">
                <p className="text-3xl font-extrabold text-goodseed-950">{survivalRate.toFixed(1)}%</p>
                <p className="text-xs font-bold text-goodseed-700">อัตรารอด</p>
              </div>
            </div>
            <div className="space-y-3">
              <AnalyticsBar label="ต้นไม้ปกติ" value={totalNormal} max={Math.max(1, totalTrees)} suffix="ต้น" note="Normal" />
              <AnalyticsBar label="ต้นไม้ผิดปกติ" value={totalAbnormal} max={Math.max(1, totalTrees)} suffix="ต้น" note="Abnormal" danger />
              <AnalyticsBar label="แถวที่ตรวจวันนี้" value={rowsInspected} max={128} suffix="แถว" note="Tree Inspection" />
            </div>
          </div>
        </DashboardPanel>

        <DashboardPanel id="analytics-progress" title="Work Progress Dashboard / แผนงานและสถานะ">
          <div className="space-y-4">
            {workStatusRows.map((row) => <AnalyticsBar key={row.label} label={row.label} value={row.value} max={maxStatus} suffix="งาน" note="Responsibility + Farm Work Planning" />)}
          </div>
        </DashboardPanel>

        <DashboardPanel id="analytics-risk" title="Problem / Risk Heatmap / แปลงเสี่ยง">
          <div className="grid gap-3 sm:grid-cols-2">
            {riskRows.map((row) => (
              <div key={`${row.plot}-${row.row}`} className={`rounded-lg p-4 ring-1 ${row.score >= 35 ? "bg-red-50 text-red-900 ring-red-100" : row.score >= 20 ? "bg-amber-50 text-amber-900 ring-amber-100" : "bg-goodseed-50 text-goodseed-900 ring-goodseed-100"}`}>
                <div className="flex items-center justify-between gap-3">
                  <p className="font-extrabold">{row.plot} / {row.row}</p>
                  <span className="rounded-full bg-white px-2 py-1 text-xs font-extrabold">{row.score}</span>
                </div>
                <p className="mt-2 text-sm font-bold">{row.issue}</p>
              </div>
            ))}
          </div>
        </DashboardPanel>
      </div>

      <DashboardPanel id="analytics-table" title="Table Summary / ข้อมูลที่ใช้คำนวณ">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[960px] text-left text-sm">
            <thead className="bg-goodseed-50 text-goodseed-900">
              <tr>
                {["Date", "Reporter", "Work Type", "Plot / Row", "Status", "Trees", "Rows", "Labor", "Cost", "Issue"].map((head) => <th key={head} className="px-3 py-3 font-extrabold">{head}</th>)}
              </tr>
            </thead>
            <tbody className="divide-y divide-goodseed-100">
              {scopedReports.map((report) => (
                <tr key={report.id} className="align-top">
                  <td className="px-3 py-3 font-bold text-goodseed-800">{report.date}</td>
                  <td className="px-3 py-3 font-bold text-goodseed-800">{report.reporter}</td>
                  <td className="px-3 py-3 font-bold text-goodseed-800">{report.workType || "Daily Report"}</td>
                  <td className="px-3 py-3 font-bold text-goodseed-800">{report.plotId || report.area} / {report.rowId || report.plotZone}</td>
                  <td className="px-3 py-3"><Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{report.workStatus || "Submitted"}</Badge></td>
                  <td className="px-3 py-3 font-bold text-goodseed-800">{analyticsNumber(report.treesPlanted).toLocaleString("th-TH")}</td>
                  <td className="px-3 py-3 font-bold text-goodseed-800">{analyticsNumber(report.rowsInspected).toLocaleString("th-TH")}</td>
                  <td className="px-3 py-3 font-bold text-goodseed-800">{analyticsNumber(report.laborCount).toLocaleString("th-TH")}</td>
                  <td className="px-3 py-3 font-bold text-goodseed-800">{analyticsNumber(report.dailyCost).toLocaleString("th-TH")}</td>
                  <td className="px-3 py-3 font-bold text-goodseed-700">{report.issue || report.qrIssue || "-"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </DashboardPanel>
    </section>
  );
}

function AnalyticsBar({ label, value, max, suffix, note, danger = false }) {
  const percent = Math.min(100, Math.round((analyticsNumber(value) / Math.max(1, analyticsNumber(max, 1))) * 100));
  return (
    <div>
      <div className="mb-2 flex items-start justify-between gap-3">
        <div>
          <p className="font-extrabold text-goodseed-950">{label}</p>
          {note && <p className="text-xs font-bold text-goodseed-600">{note}</p>}
        </div>
        <p className={`shrink-0 text-sm font-extrabold ${danger ? "text-red-700" : "text-goodseed-800"}`}>{analyticsNumber(value).toLocaleString("th-TH", { maximumFractionDigits: 1 })} {suffix}</p>
      </div>
      <div className="h-3 overflow-hidden rounded-full bg-goodseed-50">
        <div className={`h-full rounded-full ${danger ? "bg-red-500" : "bg-goodseed-600"}`} style={{ width: `${percent}%` }} />
      </div>
    </div>
  );
}

const uiFlowNodes = [
  { id: "public-home-node", name: "Public Home", type: "Page", route: "#public-home", source: "Public Website", target: "Home", label: "Home", component: "PublicWebsite", file: "src/app.jsx:3320", rolePermission: "Public", status: "Completed", notes: "Hero, CTA, farm KPI summary and Coming Soon highlight.", x: 40, y: 70 },
  { id: "cta-products", name: "ดูสินค้า / View Products", type: "Button", route: "#public-products", source: "Public Home", target: "Products Page", label: "ดูสินค้า", component: "PublicWebsite", file: "src/app.jsx:3390", rolePermission: "Public", status: "Completed", notes: "CTA link from Hero to products section.", x: 300, y: 70 },
  { id: "public-products-node", name: "Products Page", type: "Page", route: "#public-products", source: "Public Website", target: "Products", label: "Products", component: "PublicWebsite", file: "src/app.jsx:3520", rolePermission: "Public", status: "Completed", notes: "Main landscape tree section and supporting products.", x: 560, y: 70 },
  { id: "cta-company", name: "Company Profile CTA", type: "Button", route: "#public-company-profile", source: "Public Home", target: "Company Profile", label: "Company Profile", component: "PublicWebsite", file: "src/app.jsx:3391", rolePermission: "Public", status: "Completed", notes: "Hero secondary CTA.", x: 300, y: 180 },
  { id: "company-profile-node", name: "Company Profile", type: "Page", route: "#public-company-profile", source: "Public Website", target: "Download Center", label: "Company Profile", component: "PublicWebsite", file: "src/app.jsx:3650", rolePermission: "Public", status: "Completed", notes: "ศูนย์รวมเอกสารและข้อมูลเผยแพร่ของฟาร์ม พร้อมระบบดูไฟล์ ดาวน์โหลด และจัดการสถานะการแสดงผล.", x: 560, y: 180 },
  { id: "profile-download", name: "PDF Company Profile", type: "Download File", route: "download://company-profile.pdf", source: "Company Profile", target: "PDF File", label: "PDF Company Profile", component: "PublicWebsite", file: "src/app.jsx:3658", rolePermission: "Public", status: "Need Link Setup", notes: "Button exists as mock download card; actual PDF target should be attached later.", x: 820, y: 180 },
  { id: "contact-node", name: "Contact Us", type: "Page", route: "#public-contact", source: "Public Website", target: "Contact", label: "Contact Us", component: "PublicWebsite", file: "src/app.jsx:3668", rolePermission: "Public", status: "Completed", notes: "Contact info and map direction buttons.", x: 40, y: 320 },
  { id: "maps-button", name: "เปิดใน Google Maps", type: "Button", route: goodSeedMapsLink, source: "Contact Us", target: "Google Maps", label: "เปิดใน Google Maps", component: "PublicWebsite", file: "src/app.jsx:3705", rolePermission: "Public", status: "Completed", notes: "External link opens map in new tab.", x: 300, y: 320 },
  { id: "maps-external", name: "Google Maps Link", type: "External Link", route: goodSeedMapsLink, source: "Contact Us", target: "Google Maps", label: "Google Maps", component: "External", file: "src/app.jsx:3307", rolePermission: "Public", status: "Completed", notes: "maps.app.goo.gl route to GOODSEED Farm.", x: 560, y: 320 },
  { id: "login-page-node", name: "Login Page", type: "Page", route: "#login", source: "Public Website", target: "Auth Check", label: "Login", component: "LoginPage", file: "src/app.jsx:3770", rolePermission: "Public", status: "Completed", notes: "Single login box. Role is resolved from account.", x: 40, y: 520 },
  { id: "auth-check", name: "Auth Check / RBAC", type: "Role Permission", route: "role://auth-check", source: "Login Page", target: "Role-Based Dashboard", label: "Auth Check", component: "App", file: "src/app.jsx:4310", rolePermission: "Owner, Admin, Manager, Staff, Customer, Developer", status: "Completed", notes: "Routes users to visible menu based on pagePermissions.", x: 300, y: 520 },
  { id: "sidebar-menu-node", name: "Role-Based Sidebar Menu", type: "Button", route: "menu://sidebar", source: "Internal System", target: "Visible Routes", label: "Sidebar Menu", component: "Sidebar", file: "src/app.jsx:1120", rolePermission: "Owner, Admin, Manager, Staff, Customer, Developer", status: "Completed", notes: "Shows or hides internal menu items by role permission.", x: 560, y: 640 },
  { id: "dashboard-node", name: "Internal Dashboard", type: "Page", route: "#dashboard", source: "Internal System", target: "Dashboard", label: "Dashboard", component: "Dashboard", file: "src/app.jsx:1263", rolePermission: "Owner, Admin, Manager, Staff, Customer", status: "Completed", notes: "Smart Farm Control Center summary.", x: 560, y: 520 },
  { id: "tree-card", name: "ต้นไม้ทั้งหมด Card", type: "Button", route: "#tree-management", source: "Dashboard", target: "Tree Management", label: "ต้นไม้ทั้งหมด", component: "Dashboard", file: "src/app.jsx:1263", rolePermission: "Owner, Admin, Manager, Staff, Customer", status: "Completed", notes: "Overview card opens tree management detail page.", x: 820, y: 430 },
  { id: "tree-page-node", name: "Tree Management", type: "Page", route: "#tree-management", source: "Internal System", target: "Tree Management", label: "Tree Management", component: "TreeManagementPage", file: "src/app.jsx:4366", rolePermission: "Owner, Admin, Manager, Staff, Customer", status: "Completed", notes: "Tree ID, QR, species and growth tracking.", x: 1080, y: 430 },
  { id: "daily-report-node", name: "Daily Report Page", type: "Page", route: "#daily-report", source: "Internal System", target: "Google Form Style Daily Report", label: "Daily Report", component: "DailyReportPage", file: "src/app.jsx:2140", rolePermission: "Owner, Admin, Manager, Staff", status: "Completed", notes: "Daily report form with weather card and QR scan section.", x: 40, y: 830 },
  { id: "daily-report-form", name: "ส่งรายงานประจำวัน Form", type: "Form", route: "form://daily-report-submit", source: "Daily Report", target: "Dashboard Realtime Summary", label: "ส่งรายงาน", component: "ReportForm", file: "src/app.jsx:2140", rolePermission: "Owner, Admin, Manager, Staff", status: "Completed", notes: "Submit report, QR data, photos and weather notes to latest dashboard report.", x: 300, y: 830 },
  { id: "owner-export-node", name: "Owner Review Downloads", type: "Download File", route: "download://owner-review-pdf-excel-word", source: "Owner Review", target: "PDF / Excel / Word / Image", label: "Export PDF / Excel / Word", component: "OwnerReview", file: "src/app.jsx:2440", rolePermission: "Owner, Admin, Manager", status: "Completed", notes: "Download and export buttons for farm owner review.", x: 560, y: 830 },
  { id: "documents-node", name: "Documents Center", type: "Page", route: "#documents-center", source: "Internal System", target: "Documents Center", label: "Documents Center", component: "DocumentsCenterPage", file: "src/app.jsx:4120", rolePermission: "Owner, Admin, Manager, Staff", status: "Completed", notes: "Document card grid and table view.", x: 820, y: 590 },
  { id: "upload-doc-button", name: "Upload Document Button", type: "Button", route: "modal://upload-document", source: "Documents Center", target: "Upload Document Modal", label: "Upload Document", component: "DocumentsCenterPage", file: "src/app.jsx:4148", rolePermission: "Owner, Admin, Manager", status: "Completed", notes: "Opens upload slide/modal panel.", x: 1080, y: 590 },
  { id: "upload-doc-modal", name: "Upload Document Modal", type: "Modal", route: "modal://upload-document", source: "Documents Center", target: "Document Upload", label: "Upload Modal", component: "UploadDocumentPanel", file: "src/app.jsx:4040", rolePermission: "Owner, Admin, Manager", status: "Completed", notes: "Drag & drop, metadata, file type, access, Google links.", x: 1080, y: 710 },
  { id: "finance-node", name: "Financial", type: "Page", route: "#finance", source: "Internal System", target: "Financial Dashboard", label: "Financial", component: "FinanceDashboard", file: "src/app.jsx:2601", rolePermission: "Owner, Admin, Manager, Staff", status: "Completed", notes: "Revenue, OPEX, COGS, CAPEX, unit cost and import flow by role.", x: 40, y: 710 },
  { id: "import-excel-button", name: "Import Excel Button", type: "Button", route: "modal://import-excel", source: "Financial", target: "Import Excel Modal", label: "Import Excel", component: "FinanceDashboard", file: "src/app.jsx:2803", rolePermission: "Owner, Admin, Manager", status: "Completed", notes: "Excel import action in top bar and summary cards.", x: 300, y: 710 },
  { id: "import-excel-modal", name: "Import Accounting Data Modal", type: "Modal", route: "modal://import-excel", source: "Financial", target: "Accounting Data Preview", label: "Import Accounting Data", component: "FinanceDashboard", file: "src/app.jsx:2820", rolePermission: "Owner, Admin, Manager", status: "Completed", notes: "File upload, sheet select, preview and column mapping.", x: 560, y: 710 },
  { id: "people-node", name: "People / HR", type: "Page", route: "#people-hr", source: "Internal System", target: "People Dashboard", label: "People / HR", component: "PeopleHrPage", file: "src/app.jsx:3162", rolePermission: "Owner, Admin, Manager, Staff", status: "Completed", notes: "Smart workforce dashboard.", x: 820, y: 70 },
  { id: "employee-card", name: "Employee Card", type: "Button", route: "panel://employee-detail", source: "People / HR", target: "Employee Detail Slide Panel", label: "ดูโปรไฟล์", component: "EmployeeCard", file: "src/app.jsx:3102", rolePermission: "Owner, Admin, Manager, Staff", status: "Completed", notes: "Click employee card to open slide panel.", x: 1080, y: 70 },
  { id: "employee-panel", name: "Employee Detail Slide Panel", type: "Slide Panel", route: "panel://employee-detail", source: "People / HR", target: "Employee Profile", label: "Slide Panel", component: "PeopleHrPage", file: "src/app.jsx:3260", rolePermission: "Owner, Admin, Manager, Staff", status: "Completed", notes: "Profile, KPI, latest report, schedule, documents, welfare and history.", x: 1080, y: 190 },
  { id: "ui-flow-node", name: "UI Flow Map", type: "Page", route: "#ui-flow-map", source: "Developer Tools", target: "Link Mapping Diagram", label: "UI Flow Map", component: "UiFlowMapPage", file: "src/app.jsx", rolePermission: "Owner, Admin, Developer", status: "Completed", notes: "Developer-only map of routes, buttons, modals, panels and links.", x: 820, y: 710 },
  { id: "preview-deployment-node", name: "Preview Deployment", type: "Page", route: "#preview-deployment", source: "Developer Tools", target: "Share Preview Link", label: "Preview Deployment", component: "PreviewDeploymentPage", file: "src/app.jsx", rolePermission: "Owner, Admin, Developer", status: "Completed", notes: "Staging preview, access control, developer review and feedback workflow.", x: 820, y: 830 },
  { id: "comment-mode-node", name: "Comment Marker Form", type: "Form", route: "form://preview-feedback", source: "Preview Deployment", target: "Feedback Queue", label: "Comment Mode", component: "ReviewModeOverlay", file: "src/app.jsx", rolePermission: "Owner, Admin, Developer, Reviewer", status: "Completed", notes: "Click UI position, add feedback, attach screenshot name and sync into preview feedback table.", x: 1080, y: 710 },
  { id: "developer-only", name: "Developer-only Permission", type: "Role Permission", route: "role://developer-tools", source: "Developer Tools", target: "UI Flow Map", label: "Owner/Admin/Developer", component: "pagePermissions", file: "src/app.jsx:300", rolePermission: "Owner, Admin, Developer", status: "Completed", notes: "Hidden from Manager, Staff and Customer.", x: 1080, y: 830 },
  { id: "legacy-qr-link", name: "Removed Contact QR", type: "Broken Link", route: "removed://contact-map-qr", source: "Contact Us", target: "Removed QR Code", label: "QR Map", component: "PublicWebsite", file: "src/app.jsx", rolePermission: "Public", status: "Broken Link", notes: "QR section was intentionally removed from Contact / Map section.", x: 820, y: 320 },
];

const uiFlowEdges = [
  ["public-home-node", "cta-products", "ดูสินค้า"],
  ["cta-products", "public-products-node", "#public-products"],
  ["public-home-node", "cta-company", "Company Profile"],
  ["cta-company", "company-profile-node", "#public-company-profile"],
  ["company-profile-node", "profile-download", "Download"],
  ["contact-node", "maps-button", "เปิดใน Google Maps"],
  ["maps-button", "maps-external", "External"],
  ["contact-node", "legacy-qr-link", "Removed"],
  ["login-page-node", "auth-check", "Login"],
  ["auth-check", "sidebar-menu-node", "Role-Based"],
  ["sidebar-menu-node", "dashboard-node", "Dashboard"],
  ["dashboard-node", "tree-card", "Card Click"],
  ["tree-card", "tree-page-node", "#tree-management"],
  ["sidebar-menu-node", "daily-report-node", "#daily-report"],
  ["daily-report-node", "daily-report-form", "Submit"],
  ["daily-report-form", "dashboard-node", "Realtime"],
  ["dashboard-node", "owner-export-node", "Export"],
  ["dashboard-node", "documents-node", "Sidebar"],
  ["sidebar-menu-node", "documents-node", "#documents-center"],
  ["documents-node", "upload-doc-button", "Upload"],
  ["upload-doc-button", "upload-doc-modal", "Modal"],
  ["dashboard-node", "finance-node", "Sidebar"],
  ["sidebar-menu-node", "finance-node", "#finance"],
  ["finance-node", "import-excel-button", "Import"],
  ["import-excel-button", "import-excel-modal", "Modal"],
  ["dashboard-node", "people-node", "Sidebar"],
  ["sidebar-menu-node", "people-node", "#people-hr"],
  ["people-node", "employee-card", "Card Click"],
  ["employee-card", "employee-panel", "Slide Panel"],
  ["sidebar-menu-node", "ui-flow-node", "Developer Tools"],
  ["ui-flow-node", "developer-only", "RBAC"],
  ["sidebar-menu-node", "preview-deployment-node", "Developer Tools"],
  ["preview-deployment-node", "comment-mode-node", "Comment Mode"],
  ["preview-deployment-node", "developer-only", "RBAC"],
].map(([from, to, label]) => ({ from, to, label }));

const uiFlowTypeClasses = {
  Page: "border-goodseed-200 bg-goodseed-50 text-goodseed-950",
  Button: "border-amber-200 bg-amber-50 text-amber-900",
  Modal: "border-orange-200 bg-orange-50 text-orange-900",
  "Slide Panel": "border-purple-200 bg-purple-50 text-purple-900",
  "External Link": "border-slate-200 bg-slate-50 text-slate-800",
  "Download File": "border-blue-200 bg-blue-50 text-blue-900",
  Form: "border-teal-200 bg-teal-50 text-teal-900",
  "Role Permission": "border-slate-950 bg-slate-950 text-white",
  "Broken Link": "border-red-300 bg-red-50 text-red-800",
};

const uiFlowStatusClasses = {
  Completed: "bg-goodseed-100 text-goodseed-800 ring-goodseed-200",
  "In Progress": "bg-blue-100 text-blue-700 ring-blue-200",
  "Need Link Setup": "bg-amber-100 text-amber-800 ring-amber-200",
  "Broken Link": "bg-red-100 text-red-700 ring-red-200",
};

function UiFlowMapPage({ role }) {
  const [query, setQuery] = useState("");
  const [typeFilter, setTypeFilter] = useState("ทั้งหมด");
  const [roleFilter, setRoleFilter] = useState("ทั้งหมด");
  const [statusFilter, setStatusFilter] = useState("ทั้งหมด");
  const [zoom, setZoom] = useState(0.9);
  const [selectedNode, setSelectedNode] = useState(uiFlowNodes[0]);
  const [positions, setPositions] = useState(() => Object.fromEntries(uiFlowNodes.map((node) => [node.id, { x: node.x, y: node.y }])));
  const nodeTypes = ["ทั้งหมด", ...Array.from(new Set(uiFlowNodes.map((node) => node.type)))];
  const roleFilters = ["ทั้งหมด", "Public", "Owner", "Admin", "Developer", "Manager", "Staff", "Customer"];
  const statuses = ["ทั้งหมด", "Completed", "In Progress", "Need Link Setup", "Broken Link"];
  const filteredNodes = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    return uiFlowNodes.filter((node) => {
      const text = [node.name, node.type, node.route, node.source, node.target, node.label, node.component, node.rolePermission, node.status, node.notes].join(" ").toLowerCase();
      const matchesQuery = !normalized || text.includes(normalized);
      const matchesType = typeFilter === "ทั้งหมด" || node.type === typeFilter;
      const matchesRole = roleFilter === "ทั้งหมด" || node.rolePermission.toLowerCase().includes(roleFilter.toLowerCase());
      const matchesStatus = statusFilter === "ทั้งหมด" || node.status === statusFilter || (statusFilter === "Broken Link" && node.type === "Broken Link");
      return matchesQuery && matchesType && matchesRole && matchesStatus;
    });
  }, [query, typeFilter, roleFilter, statusFilter]);
  const visibleIds = useMemo(() => new Set(filteredNodes.map((node) => node.id)), [filteredNodes]);
  const visibleEdges = uiFlowEdges.filter((edge) => visibleIds.has(edge.from) && visibleIds.has(edge.to));
  const startDrag = (event, id) => {
    const startX = event.clientX;
    const startY = event.clientY;
    const start = positions[id];
    const move = (moveEvent) => {
      const nextX = Math.max(0, Math.min(1160, start.x + (moveEvent.clientX - startX) / zoom));
      const nextY = Math.max(0, Math.min(850, start.y + (moveEvent.clientY - startY) / zoom));
      setPositions((current) => ({ ...current, [id]: { x: nextX, y: nextY } }));
    };
    const up = () => {
      window.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", up);
    };
    window.addEventListener("pointermove", move);
    window.addEventListener("pointerup", up);
  };
  const exportMapping = (format = "csv") => {
    const rows = [["Node Name", "Type", "Route Path", "Source Page", "Target Page", "Button Label", "Component Name", "File Location", "Role Permission", "Status", "Notes"], ...uiFlowNodes.map((node) => [node.name, node.type, node.route, node.source, node.target, node.label, node.component, node.file, node.rolePermission, node.status, node.notes])];
    const csv = rows.map((row) => row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(",")).join("\n");
    downloadFile(`goodseed-ui-link-mapping.${format === "excel" ? "csv" : "csv"}`, `\uFEFF${csv}`, "text/csv;charset=utf-8");
  };
  const exportPng = () => {
    const canvas = document.createElement("canvas");
    canvas.width = 1400;
    canvas.height = 980;
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "#f6fbf4";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#102a18";
    ctx.font = "bold 28px sans-serif";
    ctx.fillText("GOODSEED Farm UI Flow Map / Link Mapping Diagram", 40, 55);
    ctx.font = "14px sans-serif";
    ctx.fillText("Exported mock developer map: routes, pages, buttons, modals, panels and links", 40, 82);
    filteredNodes.forEach((node) => {
      const position = positions[node.id];
      ctx.fillStyle = node.status === "Broken Link" || node.type === "Broken Link" ? "#fee2e2" : node.type === "Button" ? "#fef3c7" : node.type === "Modal" ? "#ffedd5" : node.type === "Slide Panel" ? "#f3e8ff" : node.type === "Role Permission" ? "#111827" : "#dcfce7";
      ctx.strokeStyle = node.status === "Broken Link" || node.type === "Broken Link" ? "#dc2626" : "#2f6f3a";
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.roundRect(position.x + 40, position.y + 80, 190, 64, 12);
      ctx.fill();
      ctx.stroke();
      ctx.fillStyle = node.type === "Role Permission" ? "#ffffff" : "#102a18";
      ctx.font = "bold 13px sans-serif";
      ctx.fillText(node.name.slice(0, 24), position.x + 52, position.y + 108);
      ctx.font = "11px sans-serif";
      ctx.fillText(node.type, position.x + 52, position.y + 130);
    });
    const link = document.createElement("a");
    link.download = "goodseed-ui-flow-map.png";
    link.href = canvas.toDataURL("image/png");
    link.click();
  };
  return (
    <section id="ui-flow-map" className="space-y-5">
      <SectionHeader
        title="UI Flow Map / Link Mapping Diagram"
        subtitle="Developer-only diagram สำหรับดูการเชื่อมโยง Routes, Pages, Buttons, Cards, Modals, Slide Panels, External Links และ Download Links"
        action={<Badge className="bg-slate-950 text-white ring-slate-950">Developer-only</Badge>}
      />
      <div className="grid gap-4 xl:grid-cols-5">
        <DashboardPanel className="xl:col-span-4" title="Flow Controls">
          <div className="grid gap-3 md:grid-cols-5">
            <label className="md:col-span-2 text-sm font-extrabold text-goodseed-900">Search
              <input value={query} onChange={(event) => setQuery(event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="ค้นหาหน้า / ปุ่ม / Route / Component" />
            </label>
            <Select label="Node Type" value={typeFilter} onChange={setTypeFilter} options={nodeTypes} />
            <Select label="Role Permission" value={roleFilter} onChange={setRoleFilter} options={roleFilters} />
            <Select label="Status" value={statusFilter} onChange={setStatusFilter} options={statuses} />
          </div>
          <div className="mt-4 flex flex-wrap items-center gap-3">
            <button onClick={() => setZoom((current) => Math.max(0.6, Number((current - 0.1).toFixed(1))))} className="rounded-xl border border-goodseed-100 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800">Zoom Out</button>
            <Badge className="bg-goodseed-100 text-goodseed-800 ring-goodseed-200">{Math.round(zoom * 100)}%</Badge>
            <button onClick={() => setZoom((current) => Math.min(1.4, Number((current + 0.1).toFixed(1))))} className="rounded-xl border border-goodseed-100 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800">Zoom In</button>
            <button onClick={() => setStatusFilter("Broken Link")} className="rounded-xl bg-red-50 px-4 py-2 text-sm font-extrabold text-red-700 ring-1 ring-red-100">แสดง Broken Link</button>
            <button onClick={() => setStatusFilter("Need Link Setup")} className="rounded-xl bg-amber-50 px-4 py-2 text-sm font-extrabold text-amber-800 ring-1 ring-amber-100">แสดง Need Link Setup</button>
          </div>
        </DashboardPanel>
        <DashboardPanel title="Export">
          <div className="grid gap-2">
            <button onClick={exportPng} className="rounded-xl bg-goodseed-700 px-4 py-3 text-sm font-extrabold text-white">Export PNG</button>
            <button onClick={() => window.print()} className="rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800">Export PDF / Print</button>
            <button onClick={() => exportMapping("csv")} className="rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800">Export CSV</button>
            <button onClick={() => exportMapping("excel")} className="rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-extrabold text-goodseed-800">Export Excel</button>
          </div>
        </DashboardPanel>
      </div>
      <div className="grid gap-5 xl:grid-cols-[1fr_360px]">
        <DashboardPanel title="Interactive Flow Diagram" action={<Badge className={roleInfo(role).badge}>{roleInfo(role).label}</Badge>}>
          <div className="thin-scrollbar overflow-auto rounded-2xl border border-goodseed-100 bg-[radial-gradient(circle_at_1px_1px,#dbeed4_1px,transparent_0)] bg-[length:28px_28px] p-4">
            <div style={{ width: 1320 * zoom, height: 940 * zoom }}>
              <div className="relative h-[940px] w-[1320px] origin-top-left" style={{ transform: `scale(${zoom})` }}>
                <svg className="absolute inset-0 h-full w-full overflow-visible">
                  <defs>
                    <marker id="ui-flow-arrow" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto" markerUnits="strokeWidth">
                      <path d="M0,0 L0,6 L9,3 z" fill="#6b7280" />
                    </marker>
                  </defs>
                  {visibleEdges.map((edge) => {
                    const from = positions[edge.from];
                    const to = positions[edge.to];
                    if (!from || !to) return null;
                    const x1 = from.x + 96;
                    const y1 = from.y + 38;
                    const x2 = to.x + 96;
                    const y2 = to.y + 38;
                    return (
                      <g key={`${edge.from}-${edge.to}`}>
                        <line x1={x1} y1={y1} x2={x2} y2={y2} stroke="#6b7280" strokeWidth="2" strokeDasharray={edge.label === "Removed" ? "6 5" : "0"} markerEnd="url(#ui-flow-arrow)" />
                        <text x={(x1 + x2) / 2} y={(y1 + y2) / 2 - 6} textAnchor="middle" className="fill-slate-500 text-[11px] font-bold">{edge.label}</text>
                      </g>
                    );
                  })}
                </svg>
                {filteredNodes.map((node) => {
                  const position = positions[node.id];
                  const tone = node.status === "Broken Link" ? uiFlowTypeClasses["Broken Link"] : uiFlowTypeClasses[node.type] || uiFlowTypeClasses.Page;
                  return (
                    <button
                      key={node.id}
                      type="button"
                      onPointerDown={(event) => startDrag(event, node.id)}
                      onClick={() => setSelectedNode(node)}
                      className={`absolute w-48 cursor-grab rounded-2xl border p-3 text-left shadow-soft transition hover:-translate-y-0.5 active:cursor-grabbing ${tone} ${selectedNode?.id === node.id ? "ring-4 ring-goodseed-200" : ""}`}
                      style={{ left: position.x, top: position.y }}
                    >
                      <div className="flex items-start justify-between gap-2">
                        <p className="text-sm font-extrabold leading-tight">{node.name}</p>
                        <span className="mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full bg-current opacity-60" />
                      </div>
                      <p className="mt-2 text-xs font-bold opacity-75">{node.type}</p>
                      <p className="mt-1 truncate text-[11px] font-semibold opacity-70">{node.route}</p>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </DashboardPanel>
        <DashboardPanel title="Node Detail Side Panel">
          {selectedNode ? (
            <div className="space-y-3 text-sm">
              <div className="rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4">
                <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-goodseed-500">Selected Node</p>
                <h3 className="mt-2 text-2xl font-extrabold text-goodseed-950">{selectedNode.name}</h3>
                <div className="mt-3 flex flex-wrap gap-2">
                  <Badge className={uiFlowStatusClasses[selectedNode.status] || "bg-slate-100 text-slate-700 ring-slate-200"}>{selectedNode.status}</Badge>
                  <Badge className={selectedNode.type === "Role Permission" ? "bg-slate-950 text-white ring-slate-950" : "bg-white text-goodseed-800 ring-goodseed-100"}>{selectedNode.type}</Badge>
                </div>
              </div>
              {[
                ["Route Path", selectedNode.route],
                ["Source Page", selectedNode.source],
                ["Target Page", selectedNode.target],
                ["Button Label", selectedNode.label],
                ["Component Name", selectedNode.component],
                ["File Location", selectedNode.file],
                ["Role Permission", selectedNode.rolePermission],
                ["Notes", selectedNode.notes],
              ].map(([label, value]) => (
                <div key={label} className="rounded-xl border border-goodseed-100 bg-white p-3">
                  <p className="text-xs font-extrabold uppercase tracking-[0.12em] text-goodseed-500">{label}</p>
                  <p className="mt-1 break-words font-bold leading-6 text-goodseed-900">{value}</p>
                </div>
              ))}
              <a href={selectedNode.route.startsWith("#") ? selectedNode.route : "#ui-flow-map"} className="inline-flex w-full min-h-11 items-center justify-center rounded-xl bg-goodseed-700 px-4 py-3 text-sm font-extrabold text-white">
                ไปยัง Route / Focus Target
              </a>
            </div>
          ) : (
            <p className="text-sm font-semibold text-goodseed-700">คลิก Node เพื่อดูรายละเอียด</p>
          )}
        </DashboardPanel>
      </div>
      <DashboardPanel title="Legend">
        <div className="grid gap-3 md:grid-cols-4 xl:grid-cols-8">
          {Object.entries(uiFlowTypeClasses).map(([type, className]) => (
            <div key={type} className={`rounded-xl border p-3 text-sm font-extrabold ${className}`}>{type}</div>
          ))}
        </div>
      </DashboardPanel>
    </section>
  );
}

const previewEnvironments = [
  { name: "Development", url: "http://127.0.0.1:4182", status: "Local", tone: "bg-slate-100 text-slate-700 ring-slate-200", detail: "สำหรับ Developer ทดลองบนเครื่อง" },
  { name: "Staging", url: "https://goodseed-preview.vercel.app", status: "Preview", tone: "bg-blue-100 text-blue-700 ring-blue-200", detail: "สำหรับทีมงานและพนักงานทดลองใช้งาน" },
  { name: "Production", url: "https://goodseedfarm.com", status: "Live", tone: "bg-goodseed-100 text-goodseed-800 ring-goodseed-200", detail: "เว็บจริงสำหรับลูกค้าและคู่ค้า" },
];

const deploymentProviders = [
  { name: "Vercel Preview", value: "Pull Request / Push แล้วสร้าง Preview URL อัตโนมัติ", status: "Config Ready" },
  { name: "Netlify Deploy Preview", value: "รองรับ Branch Deploy และ Preview Context", status: "Config Ready" },
  { name: "Firebase Hosting Preview", value: "ใช้ Channel Preview พร้อมวันหมดอายุ", status: "Optional" },
  { name: "Render Preview", value: "ใช้ Preview Environment สำหรับ staging", status: "Optional" },
];

const previewFeedbackSeed = [
  { id: 1, route: "#public-home", type: "Layout", message: "Hero อ่านง่ายขึ้นหลังเปลี่ยนภาพ drone view", device: "Desktop", status: "Resolved", author: "คุณหวาน", x: 28, y: 32 },
  { id: 2, route: "#finance", type: "Bug", message: "ตรวจปุ่ม Import Excel บนมือถืออีกครั้ง", device: "Mobile", status: "Open", author: "Admin Farm", x: 62, y: 58 },
  { id: 3, route: "#ui-flow-map", type: "Link", message: "เพิ่ม node สำหรับ Preview Deployment แล้ว", device: "Tablet", status: "In Review", author: "Developer", x: 45, y: 46 },
];

function buildPreviewVersion() {
  const now = new Date();
  const stamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}-${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}`;
  return `gseed-preview-${stamp}`;
}

function PreviewDeploymentPage({ role, developerReviewMode, setDeveloperReviewMode, commentMode, setCommentMode, reviewComments, setReviewComments }) {
  const [previewVersion, setPreviewVersion] = useState(buildPreviewVersion);
  const [previewProvider, setPreviewProvider] = useState("Vercel Preview");
  const [accessPassword, setAccessPassword] = useState("goodseed-team");
  const [expiry, setExpiry] = useState("7 วัน");
  const [teamOnly, setTeamOnly] = useState(true);
  const [commentAccess, setCommentAccess] = useState("Owner / Admin / Developer / Reviewer");
  const previewUrl = `https://goodseed-preview.vercel.app/${previewVersion}`;
  const stagingUrl = "https://preview.goodseedfarm.dev";
  const combinedFeedback = [...previewFeedbackSeed, ...reviewComments];
  const feedbackCsv = () => {
    const rows = [["Route", "Type", "Message", "Device", "Status", "Author"], ...combinedFeedback.map((item) => [item.route, item.type, item.message, item.device, item.status, item.author])];
    downloadFile("goodseed-preview-feedback.csv", `\uFEFF${rows.map((row) => row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(",")).join("\n")}`, "text/csv;charset=utf-8");
  };
  return (
    <section id="preview-deployment" className="space-y-5">
      <SectionHeader
        title="Preview Deployment / Share Preview Link"
        subtitle="Developer-only staging workflow สำหรับส่งลิงก์ทดลองใช้งาน เก็บ Feedback และตรวจ Responsive ก่อนขึ้น Production"
        action={<Badge className={roleInfo(role).badge}>{roleInfo(role).label}</Badge>}
      />

      <div className="grid gap-5 xl:grid-cols-[1.25fr_0.75fr]">
        <DashboardPanel
          title="Preview Build"
          action={<Badge className="bg-blue-100 text-blue-700 ring-blue-200">Staging Ready</Badge>}
        >
          <div className="rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4">
            <p className="text-xs font-extrabold uppercase tracking-[0.16em] text-goodseed-500">Shareable Preview Link</p>
            <div className="mt-3 flex flex-col gap-3 lg:flex-row lg:items-center">
              <input value={previewUrl} readOnly className="min-h-12 flex-1 rounded-xl border border-goodseed-100 bg-white px-4 text-sm font-bold text-goodseed-900 outline-none" />
              <button onClick={() => navigator.clipboard?.writeText(previewUrl)} className="min-h-12 rounded-xl bg-goodseed-700 px-5 text-sm font-extrabold text-white shadow-sm">Copy Link</button>
              <a href={previewUrl} target="_blank" rel="noopener noreferrer" className="inline-flex min-h-12 items-center justify-center rounded-xl border border-goodseed-100 bg-white px-5 text-sm font-extrabold text-goodseed-800">Open Preview</a>
            </div>
            <div className="mt-4 grid gap-3 md:grid-cols-3">
              <label className="text-sm font-extrabold text-goodseed-900">Preview Version<input value={previewVersion} onChange={(event) => setPreviewVersion(event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" /></label>
              <Select label="Provider" value={previewProvider} onChange={setPreviewProvider} options={deploymentProviders.map((item) => item.name)} />
              <label className="text-sm font-extrabold text-goodseed-900">Staging Alias<input value={stagingUrl} readOnly className="mt-2 w-full rounded-xl border border-goodseed-100 bg-white px-4 py-3 text-sm font-semibold text-goodseed-800 outline-none" /></label>
            </div>
            <button onClick={() => setPreviewVersion(buildPreviewVersion())} className="mt-4 inline-flex min-h-11 items-center gap-2 rounded-xl bg-goodseed-700 px-5 text-sm font-extrabold text-white shadow-sm"><Icon name="share" className="h-4 w-4" /> Generate Preview Version</button>
          </div>
          <div className="mt-5 grid gap-3 md:grid-cols-3">
            {previewEnvironments.map((env) => (
              <div key={env.name} className="rounded-2xl border border-goodseed-100 bg-white p-4 shadow-sm">
                <div className="flex items-center justify-between gap-3">
                  <p className="text-lg font-extrabold text-goodseed-950">{env.name}</p>
                  <Badge className={env.tone}>{env.status}</Badge>
                </div>
                <p className="mt-2 break-all text-xs font-bold text-goodseed-600">{env.url}</p>
                <p className="mt-3 text-sm font-semibold leading-6 text-slate-600">{env.detail}</p>
              </div>
            ))}
          </div>
        </DashboardPanel>

        <DashboardPanel title="Access Control">
          <div className="space-y-3">
            <label className="flex items-center justify-between gap-3 rounded-2xl border border-goodseed-100 bg-goodseed-50 p-4 text-sm font-extrabold text-goodseed-900">
              จำกัดเฉพาะทีม
              <input type="checkbox" checked={teamOnly} onChange={(event) => setTeamOnly(event.target.checked)} className="h-5 w-5 accent-goodseed-700" />
            </label>
            <label className="text-sm font-extrabold text-goodseed-900">Preview Password<input value={accessPassword} onChange={(event) => setAccessPassword(event.target.value)} className="mt-2 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" /></label>
            <Select label="วันหมดอายุ" value={expiry} onChange={setExpiry} options={["24 ชั่วโมง", "3 วัน", "7 วัน", "14 วัน", "30 วัน"]} />
            <Select label="สิทธิ์ Comment" value={commentAccess} onChange={setCommentAccess} options={["Owner / Admin / Developer / Reviewer", "Owner / Admin เท่านั้น", "ทีมทั้งหมด", "ปิดรับ Comment"]} />
          </div>
        </DashboardPanel>
      </div>

      <div className="grid gap-5 xl:grid-cols-3">
        <DashboardPanel title="Deploy Preview Automatically">
          <div className="space-y-3">
            {deploymentProviders.map((provider) => (
              <div key={provider.name} className="rounded-2xl border border-goodseed-100 bg-white p-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <p className="font-extrabold text-goodseed-950">{provider.name}</p>
                    <p className="mt-1 text-sm font-semibold leading-6 text-slate-600">{provider.value}</p>
                  </div>
                  <Badge className={provider.status === "Config Ready" ? "bg-goodseed-100 text-goodseed-800 ring-goodseed-200" : "bg-slate-100 text-slate-700 ring-slate-200"}>{provider.status}</Badge>
                </div>
              </div>
            ))}
          </div>
        </DashboardPanel>

        <DashboardPanel title="Developer Review Mode">
          <div className="space-y-3">
            <button onClick={() => setDeveloperReviewMode(!developerReviewMode)} className={`flex w-full items-center justify-between rounded-2xl p-4 text-left font-extrabold ring-1 ${developerReviewMode ? "bg-slate-950 text-white ring-slate-950" : "bg-white text-goodseed-900 ring-goodseed-100"}`}>
              แสดง Component / Route / Grid / Breakpoints
              <Badge className={developerReviewMode ? "bg-white text-slate-950 ring-white" : "bg-goodseed-100 text-goodseed-800 ring-goodseed-200"}>{developerReviewMode ? "ON" : "OFF"}</Badge>
            </button>
            <button onClick={() => setCommentMode(!commentMode)} className={`flex w-full items-center justify-between rounded-2xl p-4 text-left font-extrabold ring-1 ${commentMode ? "bg-amber-500 text-white ring-amber-500" : "bg-white text-goodseed-900 ring-goodseed-100"}`}>
              Comment Mode กดตำแหน่งบน UI เพื่อแจ้ง Feedback
              <Badge className={commentMode ? "bg-white text-amber-700 ring-white" : "bg-amber-100 text-amber-800 ring-amber-200"}>{commentMode ? "ON" : "OFF"}</Badge>
            </button>
            <div className="rounded-2xl bg-goodseed-50 p-4 text-sm font-semibold leading-6 text-goodseed-800">
              เมื่อเปิด Review Mode ระบบจะแสดงชื่อ Route, Component, Breakpoint และ Grid Layout เพื่อให้ผู้พัฒนาแก้ UI ได้ตรงจุด
            </div>
          </div>
        </DashboardPanel>

        <DashboardPanel title="Multi-device Testing">
          <div className="grid gap-3">
            {previewModes.map((mode) => (
              <div key={mode.id} className="flex items-center gap-3 rounded-2xl border border-goodseed-100 bg-white p-4">
                <div className="grid h-11 w-11 place-items-center rounded-xl bg-goodseed-50 text-goodseed-800"><Icon name={mode.icon} /></div>
                <div>
                  <p className="font-extrabold text-goodseed-950">{mode.label}</p>
                  <p className="text-sm font-semibold text-slate-600">{mode.hint}</p>
                </div>
              </div>
            ))}
          </div>
        </DashboardPanel>
      </div>

      <DashboardPanel title="Feedback System" action={<button onClick={feedbackCsv} className="rounded-xl border border-goodseed-100 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800">Export Feedback CSV</button>}>
        <div className="thin-scrollbar overflow-x-auto">
          <table className="min-w-[900px] w-full text-left text-sm">
            <thead className="bg-goodseed-50 text-goodseed-800"><tr><th className="px-3 py-3">Route</th><th className="px-3 py-3">Type</th><th className="px-3 py-3">Feedback</th><th className="px-3 py-3">Device</th><th className="px-3 py-3">Status</th><th className="px-3 py-3">Author</th></tr></thead>
            <tbody className="divide-y divide-goodseed-100">
              {combinedFeedback.map((item) => (
                <tr key={`${item.id}-${item.route}`}>
                  <td className="px-3 py-3 font-bold text-goodseed-900">{item.route}</td>
                  <td className="px-3 py-3"><Badge className="bg-white text-goodseed-800 ring-goodseed-100">{item.type}</Badge></td>
                  <td className="px-3 py-3 font-semibold text-slate-700">{item.message}</td>
                  <td className="px-3 py-3">{item.device}</td>
                  <td className="px-3 py-3"><Badge className={item.status === "Open" ? "bg-red-100 text-red-700 ring-red-200" : item.status === "In Review" ? "bg-amber-100 text-amber-800 ring-amber-200" : "bg-goodseed-100 text-goodseed-800 ring-goodseed-200"}>{item.status}</Badge></td>
                  <td className="px-3 py-3">{item.author}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </DashboardPanel>
    </section>
  );
}

function ReviewModeOverlay({ appMode, activePage, pageTitle, viewMode, developerReviewMode, commentMode, setCommentMode, reviewComments, setReviewComments }) {
  const [pendingComment, setPendingComment] = useState(null);
  const [draft, setDraft] = useState({ type: "Layout", message: "", device: "Desktop", screenshot: "" });
  if (!developerReviewMode && !commentMode && reviewComments.length === 0) return null;
  const route = appMode === "public" ? window.location.hash || "#public-home" : `#${activePage}`;
  const componentName = appMode === "public" ? "PublicWebsite" : pageTitle || activePage;
  const addPendingComment = (event) => {
    if (!commentMode || event.target.closest("[data-review-ui]")) return;
    setPendingComment({ x: event.clientX, y: event.clientY, route, page: componentName });
    setDraft({ type: "Layout", message: "", device: viewMode === "mobile" ? "Mobile" : viewMode === "tablet" ? "Tablet" : "Desktop", screenshot: "" });
  };
  const saveComment = () => {
    if (!pendingComment || !draft.message.trim()) return;
    setReviewComments((current) => [
      ...current,
      {
        id: Date.now(),
        route: pendingComment.route,
        type: draft.type,
        message: draft.message.trim(),
        device: draft.device,
        status: "Open",
        author: "Preview Reviewer",
        x: Math.round((pendingComment.x / window.innerWidth) * 100),
        y: Math.round((pendingComment.y / window.innerHeight) * 100),
        screenshot: draft.screenshot,
      },
    ]);
    setPendingComment(null);
  };
  return (
    <>
      {developerReviewMode && (
        <div className="pointer-events-none fixed inset-0 z-[85] no-print">
          <div className="absolute inset-0 opacity-30" style={{ backgroundImage: "linear-gradient(rgba(40,91,34,.18) 1px, transparent 1px), linear-gradient(90deg, rgba(40,91,34,.18) 1px, transparent 1px)", backgroundSize: "80px 80px" }} />
          <div className="absolute left-4 top-4 rounded-2xl bg-slate-950/90 p-4 text-white shadow-2xl">
            <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-goodseed-200">Developer Review Mode</p>
            <p className="mt-2 text-sm font-bold">Route: {route}</p>
            <p className="text-sm font-bold">Component: {componentName}</p>
            <p className="text-sm font-bold">Breakpoint: {viewMode}</p>
            <p className="text-xs text-slate-300">Grid / Route / Button Mapping overlay active</p>
          </div>
        </div>
      )}
      {commentMode && <div className="fixed inset-0 z-[95] cursor-crosshair bg-amber-100/10 no-print" onClick={addPendingComment} />}
      {commentMode && (
        <div data-review-ui className="fixed bottom-5 left-1/2 z-[110] flex -translate-x-1/2 items-center gap-3 rounded-2xl bg-slate-950 px-4 py-3 text-sm font-extrabold text-white shadow-2xl no-print">
          <Icon name="comment" className="h-4 w-4" />
          คลิกตำแหน่งบน UI เพื่อเพิ่ม Comment
          <button onClick={() => setCommentMode(false)} className="rounded-xl bg-white px-3 py-2 text-xs text-slate-950">ปิด</button>
        </div>
      )}
      {reviewComments.map((item) => (
        <button
          data-review-ui
          key={item.id}
          type="button"
          title={item.message}
          className="fixed z-[105] grid h-8 w-8 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-amber-500 text-xs font-extrabold text-white shadow-2xl ring-4 ring-white no-print"
          style={{ left: `${item.x}%`, top: `${item.y}%` }}
        >
          !
        </button>
      ))}
      {pendingComment && (
        <div data-review-ui className="fixed inset-0 z-[120] flex items-end bg-slate-950/50 p-4 backdrop-blur-sm no-print sm:items-center sm:justify-center">
          <div className="w-full max-w-xl rounded-2xl bg-white p-5 shadow-2xl">
            <div className="flex items-start justify-between gap-3">
              <div>
                <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-goodseed-500">Comment Marker</p>
                <h3 className="mt-1 text-xl font-extrabold text-goodseed-950">เพิ่ม Feedback บนหน้าเว็บ</h3>
                <p className="mt-1 text-sm font-semibold text-slate-600">{pendingComment.route} / {pendingComment.page}</p>
              </div>
              <button onClick={() => setPendingComment(null)} className="rounded-xl bg-goodseed-50 px-3 py-2 text-sm font-extrabold text-goodseed-800">ปิด</button>
            </div>
            <div className="mt-4 grid gap-3 md:grid-cols-2">
              <Select label="ประเภท Feedback" value={draft.type} onChange={(value) => setDraft((current) => ({ ...current, type: value }))} options={["Layout", "Bug", "Broken Button", "Responsive", "Suggestion"]} />
              <Select label="Device" value={draft.device} onChange={(value) => setDraft((current) => ({ ...current, device: value }))} options={["Desktop", "Tablet", "Mobile"]} />
              <label className="md:col-span-2 text-sm font-extrabold text-goodseed-900">Feedback<textarea value={draft.message} onChange={(event) => setDraft((current) => ({ ...current, message: event.target.value }))} className="mt-2 min-h-28 w-full rounded-xl border border-goodseed-100 px-4 py-3 text-sm font-semibold outline-none focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder="เช่น ปุ่มนี้เล็กเกินไป / ข้อความซ้อนกัน / มือถือ Layout พัง" /></label>
              <label className="md:col-span-2 text-sm font-extrabold text-goodseed-900">แนบ Screenshot<input type="file" accept="image/*" onChange={(event) => setDraft((current) => ({ ...current, screenshot: event.target.files?.[0]?.name || "" }))} className="mt-2 w-full rounded-xl border border-dashed border-goodseed-200 bg-goodseed-50 px-4 py-3 text-sm font-semibold text-goodseed-800" /></label>
            </div>
            <button onClick={saveComment} className="mt-4 w-full rounded-xl bg-goodseed-700 px-5 py-3 text-sm font-extrabold text-white">บันทึก Feedback</button>
          </div>
        </div>
      )}
    </>
  );
}

const notificationReadStorageKey = "goodseed-topbar-notification-read-v1";

function readNotificationState() {
  try {
    return JSON.parse(window.localStorage?.getItem(notificationReadStorageKey) || "[]");
  } catch (error) {
    return [];
  }
}

function priorityTone(priority) {
  return priority === "High"
    ? "bg-red-100 text-red-700 ring-red-200"
    : priority === "Medium"
      ? "bg-orange-100 text-orange-800 ring-orange-200"
      : priority === "Info"
        ? "bg-sky-100 text-sky-800 ring-sky-200"
        : "bg-goodseed-100 text-goodseed-800 ring-goodseed-200";
}

function notificationTypeIcon(type) {
  if (type.includes("report")) return "file";
  if (type.includes("inventory")) return "box";
  if (type.includes("tree")) return "tree";
  if (type.includes("irrigation")) return "wrench";
  if (type.includes("calendar") || type.includes("task")) return "calendar";
  if (type.includes("experiment")) return "leaf";
  if (type.includes("approval")) return "shield";
  return "bell";
}

function flattenFarmPlannerTasks() {
  const plannerStore = readFarmPlanningTasks();
  return Object.entries(plannerStore).flatMap(([planKey, rows]) => (rows || []).map((task) => ({ ...task, planKey })));
}

function isVisibleActivityItem(item, role) {
  if (isOwnerRole(role)) return true;
  if (role === "admin" || role === "manager") return item.visibility !== "owner";
  if (role === "staff") return item.visibility === "staff" || item.owner === "คุณหวาน" || item.reporter === "คุณหวาน";
  return false;
}

function buildTopbarActivityCenter({ reports, tasks, rdExperiments, role, readIds = [], selectedDate }) {
  const plannerTasks = flattenFarmPlannerTasks();
  const latestReport = reports[0];
  const allNotifications = [
    ...tasks.filter((task) => task.status !== "เสร็จแล้ว").map((task) => ({
      id: `task-${task.id}`,
      type: task.status === "รอดำเนินการ" ? "task_due" : task.status === "มีปัญหา" ? "task_overdue" : "calendar_updated",
      priority: task.status === "มีปัญหา" ? "High" : task.status === "รอดำเนินการ" ? "Medium" : "Normal",
      title: task.status === "รอดำเนินการ" ? `${task.duty} ถึงกำหนดเวลา 10:00 น.` : task.duty,
      detail: `${task.area} | ${task.owner} | ${task.note}`,
      time: task.frequency,
      route: task.status === "รอดำเนินการ" ? "daily-work" : "responsibility",
      visibility: "staff",
      owner: task.owner,
    })),
    ...plannerTasks.filter((task) => task.status !== "Done").slice(0, 6).map((task) => ({
      id: `planner-${task.id}`,
      type: task.status === "Pending" ? "task_due" : "calendar_updated",
      priority: task.status === "Pending" ? "Medium" : "Normal",
      title: task.name,
      detail: `${task.detail || "Farm Work Planning"} | ${task.planKey}`,
      time: "Planner",
      route: "daily-report",
      visibility: "staff",
      owner: "คุณหวาน",
    })),
    ...reports.filter((report) => analyticsNumber(report.abnormal) > 0 || /เพลี้ย|ใบเหลือง|น้ำขัง|ผิดปกติ|ชื้นเกิน/.test(`${report.issue} ${report.qrIssue} ${report.standingWater}`)).map((report) => ({
      id: `tree-${report.id}`,
      type: /น้ำขัง|งดน้ำ|ระบบน้ำ|ชื้นเกิน/.test(`${report.water} ${report.standingWater} ${report.fieldWeatherNote}`) ? "irrigation_problem" : "tree_problem",
      priority: analyticsNumber(report.abnormal) >= 18 ? "High" : "Medium",
      title: `${report.rowId || report.plotZone || report.area} พบปัญหา ${report.qrIssue || report.issue || "ต้นไม้ผิดปกติ"}`,
      detail: `${analyticsNumber(report.abnormal).toLocaleString("th-TH")} ต้น | ${report.treeSpecies || "Tree Inspection"} | ${report.reporter}`,
      time: report.createdAt || report.date,
      route: "tree-management",
      visibility: "staff",
      reporter: report.reporter,
    })),
    ...reports.slice(0, 4).map((report) => ({
      id: `report-${report.id}`,
      type: "report_submitted",
      priority: "Info",
      title: `มีรายงานใหม่จาก ${report.reporter}`,
      detail: `${report.workType || "Daily Report"} | ${report.area} | ${report.date}`,
      time: report.createdAt || report.date,
      route: "owner-review",
      visibility: "staff",
      reporter: report.reporter,
    })),
    reports.length < 3 ? {
      id: "report-missing-daily",
      type: "report_missing",
      priority: "Medium",
      title: "ทีมงานยังไม่ส่งรายงานประจำวันครบทุกคน",
      detail: latestReport ? `รายงานล่าสุดจาก ${latestReport.reporter} เวลา ${latestReport.createdAt}` : "ยังไม่มีรายงานวันนี้",
      time: "วันนี้",
      route: "daily-report",
      visibility: "manager",
    } : null,
    {
      id: "inventory-low-fuel",
      type: "inventory_low",
      priority: "High",
      title: "น้ำมันคงเหลือน้อยกว่า 15%",
      detail: "คลังวัสดุควรตรวจสต็อกน้ำมันดีเซลและอุปกรณ์ภาคสนาม",
      time: "Inventory",
      route: "inventory",
      visibility: "manager",
    },
    {
      id: `calendar-updated-${todayInputValue()}`,
      type: "calendar_updated",
      priority: "Info",
      title: `มีการแก้ไขตารางงานวันที่ ${formatTopbarDate("th")}`,
      detail: "ตรวจแปลงโซน C และรอบงานระบบน้ำถูกปรับเวลา",
      time: formatBangkokDate("th", { day: "numeric", month: "short", year: "numeric" }),
      route: "daily-report",
      visibility: "staff",
      owner: "คุณหวาน",
    },
    ...rdExperiments.filter((item) => item.status === "active").slice(0, 3).map((item) => ({
      id: `experiment-${item.id}`,
      type: "experiment_update",
      priority: item.issue && !item.issue.includes("ไม่พบ") ? "Medium" : "Normal",
      title: `มีผลทดลองใหม่: ${item.name}`,
      detail: item.latestResult,
      time: item.startDate,
      route: "experiment-rd",
      visibility: "manager",
    })),
    ...tasks.filter((task) => /รอ|อนุมัติ/.test(task.note || "")).map((task) => ({
      id: `approval-${task.id}`,
      type: "owner_approval",
      priority: "High",
      title: `รอเจ้าของอนุมัติ: ${task.duty}`,
      detail: `${task.area} | ${task.note}`,
      time: "Approval",
      route: "responsibility",
      visibility: "owner",
    })),
  ].filter(Boolean).filter((item) => isVisibleActivityItem(item, role)).map((item) => ({ ...item, read: readIds.includes(item.id) }));

  const reportRows = reports.map((report) => ({
    id: `doc-${report.id}`,
    type: report.workType || (report.qrType === "QR ต้นไม้" ? "Tree Inspection" : "Daily Report"),
    title: `${report.workType || "Daily Report"} - ${report.area}`,
    detail: `${report.reporter} | ${report.date} | ${report.summary || report.issue}`,
    time: report.createdAt || report.date,
    route: report.workType === "Inventory Withdrawal" ? "inventory" : report.workType === "Experiment & R&D" ? "experiment-rd" : "owner-review",
    priority: analyticsNumber(report.abnormal) > 0 ? "Medium" : "Normal",
    read: readIds.includes(`doc-${report.id}`),
    reporter: report.reporter,
    visibility: "staff",
  })).filter((item) => isVisibleActivityItem(item, role));

  const calendarRows = [
    ...tasks.map((task) => ({
      id: `calendar-task-${task.id}`,
      title: task.duty,
      detail: `${task.area} | ${task.owner} | ${task.status}`,
      time: task.frequency === "ทุกวัน" ? "วันนี้ 10:00" : task.frequency,
      route: "daily-work",
      owner: task.owner,
      visibility: "staff",
      priority: task.status === "มีปัญหา" ? "High" : task.status === "รอดำเนินการ" ? "Medium" : "Normal",
    })),
    ...plannerTasks.slice(0, 8).map((task) => ({
      id: `calendar-planner-${task.id}`,
      title: task.name,
      detail: `${task.detail || "Farm Work Planning"} | ${task.status}`,
      time: task.planKey,
      route: "daily-report",
      owner: "คุณหวาน",
      visibility: "staff",
      priority: task.status === "Done" ? "Normal" : "Medium",
    })),
  ].filter((item) => isVisibleActivityItem(item, role));

  return {
    notifications: allNotifications,
    documents: reportRows,
    calendarItems: calendarRows,
    unreadNotifications: allNotifications.filter((item) => !item.read).length,
    unreadDocuments: reportRows.filter((item) => !item.read).length,
    selectedDateItems: calendarRows.filter((item) => item.time.includes(selectedDate) || item.time.includes("วันนี้") || item.time.includes("weekly")).slice(0, 8),
  };
}

function TopbarIconButton({ icon, label, badge, badgeClass = "bg-red-600", active, onClick }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`relative grid h-11 w-11 place-items-center rounded-lg border text-goodseed-800 shadow-sm transition ${active ? "border-goodseed-400 bg-goodseed-50 ring-4 ring-goodseed-100" : "border-goodseed-100 bg-white hover:bg-goodseed-50"}`}
      aria-label={label}
    >
      <Icon name={icon} />
      {badge > 0 && <span className={`absolute -right-1 -top-1 min-w-5 rounded-full px-1.5 text-center text-xs font-extrabold text-white ${badgeClass}`}>{badge}</span>}
    </button>
  );
}

function ActivityDropdown({ type, data, selectedDate, setSelectedDate, onClose, onOpenItem, onMarkRead, onMarkAll }) {
  if (!type) return null;
  const isNotifications = type === "notifications";
  const isDocuments = type === "documents";
  const title = isNotifications ? "Notification Center" : isDocuments ? "Reports / Documents" : "Calendar Panel";
  const subtitle = isNotifications ? "แจ้งเตือนงาน ปัญหา รายงาน คลัง และการอนุมัติ" : isDocuments ? "รายงานล่าสุดและรายการรอตรวจสอบ" : "งานสำคัญของวันที่เลือก เชื่อมกับ Farm Work Planning";
  const rows = isNotifications ? data.notifications : isDocuments ? data.documents : data.selectedDateItems;
  const allRoute = isNotifications ? "notification-center" : isDocuments ? "documents-center" : "daily-report";
  return (
    <div className="absolute right-0 top-[calc(100%+0.75rem)] z-50 w-[min(92vw,520px)] rounded-2xl border border-goodseed-100 bg-white p-4 shadow-2xl">
      <div className="flex items-start justify-between gap-3">
        <div>
          <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-goodseed-500">{title}</p>
          <h3 className="mt-1 text-lg font-extrabold text-goodseed-950">{subtitle}</h3>
        </div>
        <button type="button" onClick={onClose} className="rounded-lg bg-goodseed-50 px-3 py-2 text-sm font-extrabold text-goodseed-800">ปิด</button>
      </div>
      {type === "calendar" && (
        <div className="mt-4 grid gap-3 rounded-lg bg-goodseed-50 p-3 sm:grid-cols-[1fr_auto] sm:items-end">
          <Input label="เลือกวัน / เดือน / ปี" type="date" value={selectedDate} onChange={setSelectedDate} />
          <button type="button" onClick={() => onOpenItem({ route: "daily-report", id: "calendar-open" })} className="rounded-lg bg-goodseed-700 px-4 py-3 text-sm font-extrabold text-white">ดูปฏิทินทั้งหมด</button>
        </div>
      )}
      <div className="thin-scrollbar mt-4 max-h-[440px] space-y-3 overflow-y-auto pr-1">
        {rows.length ? rows.map((item) => (
          <div key={item.id} className={`rounded-xl border p-3 ${item.read ? "border-goodseed-100 bg-white" : "border-goodseed-200 bg-goodseed-50"}`}>
            <div className="flex items-start gap-3">
              <div className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-white text-goodseed-800 shadow-sm"><Icon name={notificationTypeIcon(item.type || "calendar")} className="h-5 w-5" /></div>
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                  <Badge className={priorityTone(item.priority)}>{item.priority || "Normal"}</Badge>
                  {item.type && <Badge className="bg-white text-goodseed-700 ring-goodseed-100">{item.type}</Badge>}
                  <span className="text-xs font-bold text-goodseed-500">{item.time}</span>
                  {!item.read && isNotifications && <span className="h-2 w-2 rounded-full bg-red-500" />}
                </div>
                <p className="mt-2 font-extrabold leading-snug text-goodseed-950">{item.title}</p>
                <p className="mt-1 text-sm font-semibold leading-relaxed text-goodseed-700">{item.detail}</p>
                <div className="mt-3 flex flex-wrap gap-2">
                  <button type="button" onClick={() => onOpenItem(item)} className="rounded-lg bg-goodseed-700 px-3 py-2 text-xs font-extrabold text-white">View Detail</button>
                  {!item.read && (isNotifications || isDocuments) && <button type="button" onClick={() => onMarkRead(item.id)} className="rounded-lg border border-goodseed-100 bg-white px-3 py-2 text-xs font-extrabold text-goodseed-800">ทำเครื่องหมายว่าอ่านแล้ว</button>}
                </div>
              </div>
            </div>
          </div>
        )) : (
          <div className="rounded-xl bg-goodseed-50 p-5 text-center font-bold text-goodseed-700">ไม่มีรายการสำหรับสิทธิ์หรือวันที่เลือก</div>
        )}
      </div>
      <div className="mt-4 flex flex-wrap justify-between gap-2 border-t border-goodseed-100 pt-3">
        <button type="button" onClick={() => onOpenItem({ route: allRoute, id: `${type}-all` })} className="rounded-lg border border-goodseed-100 bg-white px-4 py-2 text-sm font-extrabold text-goodseed-800">ดูทั้งหมด</button>
        {(isNotifications || isDocuments) && <button type="button" onClick={onMarkAll} className="rounded-lg bg-goodseed-700 px-4 py-2 text-sm font-extrabold text-white">ทำเครื่องหมายว่าอ่านแล้วทั้งหมด</button>}
      </div>
    </div>
  );
}

const internalRouteIds = new Set([
  ...navItems.map(([, , id]) => id),
  "work-planning",
  "farm-calendar",
  "farm-kpi",
  "organization-goals",
  "news-promotion",
  "company-profile",
  "plots",
  "trees",
  "daily-work",
  "responsibility",
  "report-form",
  "workers",
  "stock",
  "alerts",
  "owner-review",
]);

const pathRouteAliases = {
  "/work-planning": "work-planning",
  "/farm-calendar": "farm-calendar",
  "/farm-kpi": "farm-kpi",
};

function getLoginRoleFromUrl() {
  return null;
}

function App() {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [viewMode, setViewMode] = useState("desktop");
  const initialLoginRole = getLoginRoleFromUrl();
  const [role, setRole] = useState(initialLoginRole || "customer");
  const roleRef = useRef(initialLoginRole || "customer");
  const [authProfile, setAuthProfile] = useState(null);
  const [language, setLanguage] = useState(getStoredLanguage);
  const initialHash = window.location.hash.replace("#", "");
  const initialPathRoute = pathRouteAliases[window.location.pathname];
  const [appMode, setAppMode] = useState(() => {
    if (initialHash === "login") return "login";
    if (initialHash === "auth-status") return "auth-status";
    if (initialPathRoute || internalRouteIds.has(initialHash)) {
      if (!initialLoginRole) return "login";
      return initialLoginRole === "customer" ? "public" : "internal";
    }
    return "public";
  });
  const [activePage, setActivePage] = useState(() => initialPathRoute || (internalRouteIds.has(initialHash) ? initialHash : "dashboard"));
  const [reports, setReports] = useState(initialReports);
  const [tasks] = useState(initialTasks);
  const [rdExperiments, setRdExperiments] = useState(initialRdExperiments);
  const [developerReviewMode, setDeveloperReviewMode] = useState(false);
  const [commentMode, setCommentMode] = useState(false);
  const [reviewComments, setReviewComments] = useState([]);
  const [topbarPanel, setTopbarPanel] = useState(null);
  const [notificationReadIds, setNotificationReadIds] = useState(readNotificationState);
  const [plannerSignal, setPlannerSignal] = useState(0);
  const [selectedTopbarDate, setSelectedTopbarDate] = useState(todayInputValue);
  const addReport = (report) => setReports((current) => [report, ...current]);
  const currentRole = roleInfo(role);
  const t = (key, fallback) => translatePath(language, key) || fallback || key;
  const openPublic = () => {
    setTopbarPanel(null);
    setAppMode("public");
    window.location.href = "./index.html#public-home";
  };
  const openLogin = () => {
    setAppMode("login");
    window.location.hash = "login";
  };
  const openInternal = (nextAuth = authProfile || role) => {
    const nextProfile = typeof nextAuth === "string" ? null : nextAuth;
    const nextRole = nextProfile?.role || nextAuth || "customer";
    if (nextProfile) setAuthProfile(nextProfile);
    if (nextRole === "customer") {
      roleRef.current = "customer";
      setRole("customer");
      if (nextProfile) {
        setAppMode("auth-status");
        window.location.hash = "auth-status";
      } else {
        setAppMode("public");
        window.location.hash = "public-home";
      }
      return;
    }
    if (nextProfile && !canEnterBackend(nextProfile)) {
      roleRef.current = "customer";
      setRole("customer");
      setAppMode("auth-status");
      window.location.hash = "auth-status";
      return;
    }
    const firstPage = visibleNavItems(nextRole)[0]?.[2] || "dashboard";
    roleRef.current = nextRole;
    setRole(nextRole);
    setActivePage(firstPage);
    setAppMode("internal");
    window.setTimeout(() => {
      window.location.hash = firstPage;
      resetViewportScroll();
    }, 0);
  };
  const openInternalPage = (pageId) => {
    const nextPage = canAccess(role, pageId) ? pageId : visibleNavItems(role)[0]?.[2] || "dashboard";
    setTopbarPanel(null);
    setAppMode("internal");
    setActivePage(nextPage);
    window.location.hash = nextPage;
    window.setTimeout(resetViewportScroll, 0);
  };
  const signOut = () => {
    const client = getSupabaseClient({ silent: true });
    if (client && authProfile?.id) {
      Promise.resolve(client.from("user_presence").update({ status: "offline", last_seen_at: new Date().toISOString(), updated_at: new Date().toISOString() }).eq("user_id", authProfile.id)).catch(() => {});
    }
    setAuthProfile(null);
    roleRef.current = "customer";
    setRole("customer");
    setTopbarPanel(null);
    clearSupabaseAuthStorage();
    setAppMode("public");
    window.location.href = "./index.html#public-home";
    if (client) {
      withSupabaseTimeout(client.auth.signOut(), "signout-timeout", 5000).catch(() => {});
    }
  };

  useEffect(() => {
    try {
      localStorage.setItem("goodseed-language", language);
    } catch (error) {
      // localStorage can be unavailable when opened in strict private contexts.
    }
    document.documentElement.lang = language;
  }, [language]);

  useEffect(() => {
    const client = getSupabaseClient({ silent: true });
    if (!client) return undefined;
    let active = true;
    client.auth.getSession().then(async ({ data }) => {
      try {
        if (!active || !data?.session?.user) return;
        const profile = await loadSupabaseProfile(data.session.user);
        if (!active) return;
        setAuthProfile(profile);
        const nextRole = canEnterBackend(profile) ? profile.role : "customer";
        roleRef.current = nextRole;
        setRole(nextRole);
        if ((window.location.hash === "#login" || internalRouteIds.has(window.location.hash.replace("#", ""))) && !canEnterBackend(profile)) {
          setAppMode("auth-status");
          window.location.hash = "auth-status";
          return;
        }
        if ((window.location.hash === "#login" || internalRouteIds.has(window.location.hash.replace("#", ""))) && nextRole !== "customer") {
          const firstPage = visibleNavItems(profile.role)[0]?.[2] || "dashboard";
        setActivePage(firstPage);
        setAppMode("internal");
        window.setTimeout(() => {
          window.location.hash = firstPage;
          resetViewportScroll();
        }, 0);
      }
      } catch (error) {
        console.warn("GoodSeed session restore failed", error);
        if (active) {
          setAuthProfile(null);
          roleRef.current = "customer";
          setRole("customer");
          setAppMode("login");
          window.location.hash = "login";
        }
      }
    }).catch((error) => {
      console.warn("GoodSeed session lookup failed", error);
    });
    const { data } = client.auth.onAuthStateChange(async (_event, session) => {
      try {
        if (!session?.user) {
          if (roleRef.current !== "customer") return;
          setAuthProfile(null);
          roleRef.current = "customer";
          setRole("customer");
          return;
        }
        const profile = await loadSupabaseProfile(session.user);
        setAuthProfile(profile);
        const nextRole = canEnterBackend(profile) ? profile.role : "customer";
        roleRef.current = nextRole;
        setRole(nextRole);
      } catch (error) {
        console.warn("GoodSeed auth state sync failed", error);
      }
    });
    return () => {
      active = false;
      data?.subscription?.unsubscribe();
    };
  }, []);

  useEffect(() => {
    const client = getSupabaseClient({ silent: true });
    if (!client || !authProfile?.id || !canEnterBackend(authProfile) || !canUseBackendPresence(role)) return undefined;
    let stopped = false;
    const writePresence = async (status = "online") => {
      try {
        if (stopped) return;
        const now = new Date().toISOString();
        await client.from("user_presence").upsert({
          user_id: authProfile.id,
          email: authProfile.email || "",
          full_name: profileDisplayName(authProfile),
          role,
          current_page: activePage,
          status,
          last_seen_at: now,
          updated_at: now,
        }, { onConflict: "user_id" });
      } catch (error) {
        console.warn("GoodSeed user presence heartbeat failed", error);
      }
    };
    writePresence("online");
    const timer = window.setInterval(() => writePresence("online"), 25000);
    const handleVisibility = () => {
      if (document.visibilityState === "visible") writePresence("online");
    };
    const handleBeforeUnload = () => {
      stopped = true;
      Promise.resolve(client.from("user_presence").update({ status: "offline", last_seen_at: new Date().toISOString(), updated_at: new Date().toISOString() }).eq("user_id", authProfile.id)).catch(() => {});
    };
    document.addEventListener("visibilitychange", handleVisibility);
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => {
      stopped = true;
      window.clearInterval(timer);
      document.removeEventListener("visibilitychange", handleVisibility);
      window.removeEventListener("beforeunload", handleBeforeUnload);
      Promise.resolve(client.from("user_presence").update({ status: "offline", last_seen_at: new Date().toISOString(), updated_at: new Date().toISOString() }).eq("user_id", authProfile.id)).catch(() => {});
    };
  }, [authProfile?.id, authProfile?.email, role, activePage]);

  useEffect(() => {
    try {
      window.localStorage?.setItem(notificationReadStorageKey, JSON.stringify(notificationReadIds));
    } catch (error) {
      // Ignore storage errors in privacy-restricted contexts.
    }
  }, [notificationReadIds]);

  useEffect(() => {
    const refreshPlannerSignal = () => setPlannerSignal((value) => value + 1);
    window.addEventListener("goodseed-farm-planning-updated", refreshPlannerSignal);
    window.addEventListener("storage", refreshPlannerSignal);
    return () => {
      window.removeEventListener("goodseed-farm-planning-updated", refreshPlannerSignal);
      window.removeEventListener("storage", refreshPlannerSignal);
    };
  }, []);

  useEffect(() => {
    const handleHashChange = () => {
      const id = window.location.hash.replace("#", "");
      if (id === "auth-status") {
        setAppMode("auth-status");
        return;
      }
      if (id === "login") {
        setAppMode("login");
        return;
      }
      if (id.startsWith("public-") || !id) {
        const pathRoute = pathRouteAliases[window.location.pathname];
        if (pathRoute) {
          if (role === "customer") {
            setAppMode("login");
            window.location.hash = "login";
            return;
          }
          setAppMode("internal");
          setActivePage(pathRoute);
          return;
        }
        setAppMode("public");
        return;
      }
      if (internalRouteIds.has(id)) {
        const currentRouteRole = roleRef.current || role;
        if (currentRouteRole === "customer") {
          if (initialLoginRole === "customer") {
            setAppMode("public");
            window.location.hash = "public-home";
          } else {
            setAppMode("login");
            window.location.hash = "login";
          }
          return;
        }
        setAppMode("internal");
        setActivePage(canAccess(currentRouteRole, id) ? id : visibleNavItems(currentRouteRole)[0]?.[2] || "dashboard");
      }
      window.setTimeout(resetViewportScroll, 40);
    };
    handleHashChange();
    window.addEventListener("hashchange", handleHashChange);
    return () => window.removeEventListener("hashchange", handleHashChange);
  }, [role]);

  const topbarActivity = useMemo(() => buildTopbarActivityCenter({ reports, tasks, rdExperiments, role, readIds: notificationReadIds, selectedDate: selectedTopbarDate }), [reports, tasks, rdExperiments, role, notificationReadIds, selectedTopbarDate, plannerSignal]);
  const topbarDateLabel = formatTopbarDate(language);
  const topbarWeekdayLabel = formatTopbarWeekday(language);

  if (appMode === "public") {
    return <PublicWebsite onLogin={openLogin} language={language} setLanguage={setLanguage} t={t} role={role} />;
  }

  if (appMode === "login") {
    return <LoginPage onLogin={openInternal} onPublic={openPublic} language={language} setLanguage={setLanguage} t={t} />;
  }

  if (appMode === "auth-status") {
    return <AuthStatusPage profile={authProfile} onPublic={openPublic} onSignOut={signOut} />;
  }

  const fallbackPage = visibleNavItems(role)[0]?.[2] || "dashboard";
  const resolvedPage = canAccess(role, activePage) ? activePage : fallbackPage;
  const pageInfo = visibleNavItems(role).find(([, , id]) => id === resolvedPage);
  const pageTitle = pageInfo ? t(`internalNav.${pageInfo[2]}`, pageInfo[0]) : t(`internalNav.${resolvedPage}`, "Dashboard");
  const renderActivePage = () => {
    switch (resolvedPage) {
      case "dashboard":
        if (role === "customer") {
          return <InfoPanel id="customer-portal" title="Customer Portal" icon="tree" items={["สินค้าไม้ล้อมและผลิตภัณฑ์ฟาร์มที่เปิดเผย", "QR Tree Profile เฉพาะรายการที่อนุญาต", "Company Profile / Catalog / เอกสารที่เปิดให้ลูกค้าดาวน์โหลด", "ช่องทางติดต่อทีมขาย GOODSEED Farm"]} />;
        }
        return <Dashboard reports={reports} tasks={tasks} viewMode={viewMode} role={role} rdExperiments={rdExperiments} authProfile={authProfile} />;
      case "work-planning":
        return <DailyReportPage onSave={addReport} role={role} authProfile={authProfile} initialSection="planning" language={language} />;
      case "farm-calendar":
        return <PeopleHrPage role={role} viewMode={viewMode} initialTab="KPI / Performance" planningInitialTab="monthly" />;
      case "farm-kpi":
        return <PeopleHrPage role={role} viewMode={viewMode} initialTab="KPI / Performance" planningInitialTab="kpi" />;
      case "farm-management":
        return <FarmManagementPage role={role} />;
      case "tree-management":
        return <TreeManagementPage role={role} />;
      case "daily-report":
        return <DailyReportPage onSave={addReport} role={role} authProfile={authProfile} language={language} />;
      case "organization-goals":
        return <OrganizationGoals />;
      case "news-promotion":
        return <NewsPromotionPage role={role} />;
      case "company-profile":
        return <CompanyProfilePage role={role} />;
      case "plots":
      case "trees":
        return <FarmMapGallery />;
      case "report-form":
        return (
          <div className="space-y-5">
            <CrudGovernanceBar role={role} moduleId="forms-reports" title="Forms / Reports CRUD" />
            <ReportForm onSave={addReport} language={language} />
          </div>
        );
      case "people-hr":
        return <PeopleHrPage role={role} viewMode={viewMode} />;
      case "inventory":
        return <InventoryWarehousePage role={role} />;
      case "responsibility":
        return <ResponsibilityTable tasks={tasks} viewMode={viewMode} role={role} />;
      case "daily-work":
        return <SchedulePages role={role} />;
      case "owner-review":
        return <OwnerReview reports={reports} tasks={tasks} />;
      case "workers":
        return <InfoPanel id="workers" title="คนงาน" icon="users" items={["พี่ไกร: รดน้ำและตรวจระบบน้ำ", "พี่สมชาย: ถอนหญ้าและใส่ปุ๋ย", "ทีมรอบเย็นเริ่ม 16:00 น.", "มีรูปหลักฐาน 22 ภาพ"]} />;
      case "equipment":
        return <FarmAssetsPage role={role} />;
      case "stock":
        return <div className="space-y-5"><InfoPanel id="stock" title="สต็อกวัสดุ" icon="box" items={["ปุ๋ยอินทรีย์ 132 กระสอบ", "วัสดุคลุมดิน 18 ม้วน", "ยาป้องกันแมลง 24 ลิตร", "เบิกใช้วันนี้ 12 รายการ"]} /><StockMaterialsGuide /></div>;
      case "finance":
        return <FinanceDashboard role={role} />;
      case "experiment-rd":
        return <ExperimentRdPage rdExperiments={rdExperiments} setRdExperiments={setRdExperiments} role={role} />;
      case "documents-center":
        return <DocumentsCenterPage role={role} authProfile={authProfile} />;
      case "notification-center":
        return <NotificationCenterPage reports={reports} tasks={tasks} rdExperiments={rdExperiments} role={role} />;
      case "analytics-bi":
        return <AnalyticsBiPage reports={reports} tasks={tasks} rdExperiments={rdExperiments} role={role} />;
      case "ui-flow-map":
        return <UiFlowMapPage role={role} />;
      case "preview-deployment":
        return (
          <PreviewDeploymentPage
            role={role}
            developerReviewMode={developerReviewMode}
            setDeveloperReviewMode={setDeveloperReviewMode}
            commentMode={commentMode}
            setCommentMode={setCommentMode}
            reviewComments={reviewComments}
            setReviewComments={setReviewComments}
          />
        );
      case "user-management":
        return <OwnerUserManagementPage role={role} />;
      case "alerts":
        return <InfoPanel id="alerts" title="แจ้งเตือน" icon="bell" items={alerts.map((alert) => `${alert.level}: ${alert.title} - ${alert.detail}`)} />;
      case "settings":
        return <PermissionMatrix role={role} />;
      default:
        return <Dashboard reports={reports} tasks={tasks} viewMode={viewMode} role={role} rdExperiments={rdExperiments} />;
    }
  };
  const appShellClass = viewMode === "mobile"
    ? "mx-auto min-h-screen max-w-[430px] bg-white pb-24 shadow-2xl"
    : viewMode === "tablet"
      ? "mx-auto flex min-h-screen max-w-[920px] bg-white shadow-2xl"
      : "min-h-screen overflow-x-hidden lg:flex";
  const contentClass = viewMode === "mobile" ? "space-y-5 p-3" : viewMode === "tablet" ? "space-y-5 p-4" : "space-y-6 p-4 sm:p-6";
  const markTopbarItemRead = (id) => setNotificationReadIds((current) => current.includes(id) ? current : [...current, id]);
  const markTopbarGroupRead = () => {
    const rows = topbarPanel === "documents" ? topbarActivity.documents : topbarActivity.notifications;
    setNotificationReadIds((current) => Array.from(new Set([...current, ...rows.map((item) => item.id)])));
  };
  const openTopbarItem = (item) => {
    if (item.id) markTopbarItemRead(item.id);
    openInternalPage(item.route || "dashboard");
  };
  const headerUserName = authProfile?.fullName || authProfile?.email || "GOODSEED User";
  const headerUserEmail = authProfile?.email || "";

  return (
    <div className={appShellClass}>
      <Sidebar open={sidebarOpen} setOpen={setSidebarOpen} viewMode={viewMode} role={role} t={t} />
      <main className="min-w-0 flex-1 overflow-x-hidden">
        <header className={`sticky top-0 z-20 border-b border-goodseed-100 bg-white/90 shadow-sm backdrop-blur no-print ${viewMode === "mobile" ? "px-3 py-3" : "px-4 py-3 sm:px-6"}`}>
          <div className="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
            <div className="flex items-center gap-3">
              {viewMode !== "tablet" && viewMode !== "mobile" && <button className="rounded-lg border border-goodseed-200 bg-white p-2 text-goodseed-800 lg:hidden" onClick={() => setSidebarOpen(true)} aria-label="เปิดเมนู"><Icon name="menu" /></button>}
              <div>
                <p className="text-sm font-bold text-goodseed-700">{pageTitle}</p>
                <h1 className={`${viewMode === "mobile" ? "text-lg" : "text-lg sm:text-2xl"} font-extrabold text-goodseed-950`}>{t("topbar.systemTitle")}</h1>
              </div>
            </div>
            <div className={`flex min-w-0 flex-1 flex-col gap-3 ${viewMode === "desktop" ? "xl:max-w-5xl xl:flex-row xl:items-center" : ""}`}>
              <label className="relative flex-1">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-goodseed-400"><Icon name="qr" className="h-4 w-4" /></span>
                <input className="w-full rounded-lg border border-goodseed-100 bg-white py-3 pl-10 pr-4 text-sm font-semibold text-goodseed-900 shadow-sm outline-none transition placeholder:text-slate-400 focus:border-goodseed-500 focus:ring-4 focus:ring-goodseed-100" placeholder={t("topbar.searchPlaceholder")} />
              </label>
              <PreviewToggle viewMode={viewMode} setViewMode={setViewMode} t={t} />
              <div className="relative flex flex-wrap items-center gap-2">
                <LanguageToggle language={language} setLanguage={setLanguage} compact />
                {role !== "customer" && (
                  <>
                    <TopbarIconButton icon="bell" label="แจ้งเตือน" badge={topbarActivity.unreadNotifications} active={topbarPanel === "notifications"} onClick={() => setTopbarPanel((current) => current === "notifications" ? null : "notifications")} />
                    <TopbarIconButton icon="file" label="เอกสาร / รายงาน" badge={topbarActivity.unreadDocuments} badgeClass="bg-goodseed-600" active={topbarPanel === "documents"} onClick={() => setTopbarPanel((current) => current === "documents" ? null : "documents")} />
                  </>
                )}
                <button type="button" onClick={() => role !== "customer" && setTopbarPanel((current) => current === "calendar" ? null : "calendar")} className={`flex items-center gap-2 rounded-lg border px-3 py-2 shadow-sm transition ${topbarPanel === "calendar" ? "border-goodseed-400 bg-goodseed-50 ring-4 ring-goodseed-100" : "border-goodseed-100 bg-white hover:bg-goodseed-50"}`}>
                  <Icon name="calendar" className="h-5 w-5 text-goodseed-700" />
                  <div><p className="text-sm font-extrabold text-goodseed-950">{topbarDateLabel}</p><p className="text-xs font-bold text-goodseed-600">{topbarWeekdayLabel}</p></div>
                </button>
                {role !== "customer" && (
                  <ActivityDropdown
                    type={topbarPanel}
                    data={topbarActivity}
                    selectedDate={selectedTopbarDate}
                    setSelectedDate={setSelectedTopbarDate}
                    onClose={() => setTopbarPanel(null)}
                    onOpenItem={openTopbarItem}
                    onMarkRead={markTopbarItemRead}
                    onMarkAll={markTopbarGroupRead}
                  />
                )}
                <div className="flex items-center gap-2 rounded-lg border border-goodseed-100 bg-white px-3 py-2 shadow-sm">
                  <img src={farmLogo} alt="GoodSeed Farm logo" className="h-9 w-9 rounded-full object-cover" />
                  <div className="min-w-0">
                    <p className="max-w-[180px] truncate text-sm font-extrabold text-goodseed-950">{headerUserName}</p>
                    <p className="max-w-[180px] truncate text-xs font-bold text-goodseed-600">{headerUserEmail}</p>
                  </div>
                  <Badge className={currentRole.badge}>{currentRole.label}</Badge>
                </div>
                <button onClick={openPublic} className="rounded-lg border border-goodseed-100 bg-white px-3 py-2 text-sm font-extrabold text-goodseed-800 shadow-sm hover:bg-goodseed-50">{t("actions.publicWebsite")}</button>
                <a href="./index.html#public-home" onClick={signOut} className="rounded-lg border border-red-100 bg-red-50 px-3 py-2 text-sm font-extrabold text-red-700 shadow-sm hover:bg-red-100">Sign Out / ออกจากระบบ</a>
              </div>
            </div>
          </div>
        </header>
        <div className={contentClass}>
          {renderActivePage()}
        </div>
      </main>
      {viewMode === "mobile" && <BottomNavigation role={role} t={t} />}
      <ReviewModeOverlay
        appMode={appMode}
        activePage={resolvedPage}
        pageTitle={pageTitle}
        viewMode={viewMode}
        developerReviewMode={developerReviewMode}
        commentMode={commentMode}
        setCommentMode={setCommentMode}
        reviewComments={reviewComments}
        setReviewComments={setReviewComments}
      />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(
  <AppErrorBoundary>
    <App />
  </AppErrorBoundary>
);
