/* NutriDMS, Loraa AI · QA Review · Workflow Automation · Audit Log (v2) */

// ───── Loraa Logo (inline) ─────
function LoraaLogo({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <defs>
        <linearGradient id="laura-grad" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
          <stop offset="0%" stopColor="#3b7c0f" />
          <stop offset="50%" stopColor="#15B79E" />
          <stop offset="100%" stopColor="#2A54E5" />
        </linearGradient>
      </defs>
      <path d="M16 2 L29 9 L29 23 L16 30 L3 23 L3 9 Z" fill="url(#laura-grad)" />
      <path d="M16 8 L23 12 L23 20 L16 24 L9 20 L9 12 Z" fill="#fff" opacity="0.95" />
      <path d="M16 12 L20 14 L20 18 L16 20 L12 18 L12 14 Z" fill="url(#laura-grad)" />
    </svg>
  );
}

// ───── Ask Loraa, main AI Assistant screen ─────
const LAURA_FEATURES = [
  { id: "qa",         icon: "scan-line",       title: "QA review AI assistant",
    desc: "Automatically detects missing data, nutrition inconsistencies, allergen risks, and compliance gaps.",
    status: { label: "3 Errors detected", tone: "error" }, to: "qa-review" },
  { id: "notes",      icon: "file-pen",        title: "Recipe note writer",
    desc: "Generates cultural insights, health notes, and simplified descriptions.",
    status: { label: "Ready", tone: "info" } },
  { id: "audit",      icon: "utensils",        title: "Ingredient audit",
    desc: "Detects unused, duplicate, or incompatible ingredient combinations.",
    status: { label: "2 Warnings", tone: "warning" } },
  { id: "tags",       icon: "shield-check",    title: "Health tag validator",
    desc: "Cross-checks tags against macro and micro nutritional thresholds.",
    status: { label: "All valid", tone: "success" } },
  { id: "dupes",      icon: "copy-check",      title: "Duplicate detection",
    desc: "Detects semantically similar recipes before approval or publishing.",
    status: { label: "Ready", tone: "info" } },
];

function AskLoraaScreen() {
  const { setPage, toast, role } = useApp();
  const user = currentUser(role);
  const [query, setQuery] = React.useState("");
  const [thread, setThread] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const scrollRef = React.useRef(null);

  const send = async () => {
    const q = query.trim();
    if (!q) return;
    setQuery("");
    setThread((t) => [...t, { role: "user", text: q }]);
    setLoading(true);
    try {
      const reply = await window.claude.complete(
        `You are Loraa, an AI assistant inside NutriDMS, a nutritional content management system for recipes. ` +
        `Answer in 2-4 short sentences, friendly and concise. If asked about a specific recipe, you can invent plausible details. ` +
        `User asks: ${q}`
      );
      setThread((t) => [...t, { role: "laura", text: reply }]);
    } catch (e) {
      setThread((t) => [...t, { role: "laura", text: "I couldn't reach the model just now. Try again in a moment." }]);
    } finally {
      setLoading(false);
      setTimeout(() => scrollRef.current?.scrollTo({ top: 99999, behavior: "smooth" }), 50);
    }
  };

  const suggestions = [
    "Which recipes are missing nutrition data?",
    "Find duplicate Mediterranean recipes",
    "Audit allergens for breakfast category",
    "Summarise this week's QA flags",
  ];

  return (
    <div>
      <Crumbs path={[{ label: "Dashboard", onClick: () => setPage("dashboard") }, { label: "Loraa AI" }]} />
      <div className="page-head">
        <div>
          <h1 className="page-title">AI Assistant</h1>
          <p className="page-sub">Scan every recipe for issues across ingredients, nutrition, and compliance.</p>
        </div>
      </div>

      {/* Hero chat block */}
      <div className="card pad" style={{ padding: 32, background: "linear-gradient(180deg, #FAFCFB 0%, #FFFFFF 60%)" }}>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", marginBottom: 22 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
            <LoraaLogo size={36} />
            <span style={{ fontFamily: "var(--serif)", fontSize: 26, color: "var(--brand-700)", letterSpacing: "-.01em" }}>Ask Loraa</span>
          </div>
          <h2 style={{ fontFamily: "var(--serif)", fontSize: 30, margin: 0, color: "var(--text-primary)" }}>Welcome back, {user.name.split(" ")[0]}</h2>
        </div>

        {/* Thread */}
        {thread.length > 0 && (
          <div ref={scrollRef} style={{ maxHeight: 320, overflowY: "auto", marginBottom: 14, padding: "8px 4px" }}>
            {thread.map((msg, i) => (
              <div key={i} style={{ display: "flex", gap: 12, marginBottom: 14, justifyContent: msg.role === "user" ? "flex-end" : "flex-start" }}>
                {msg.role === "laura" && <div style={{ flexShrink: 0 }}><LoraaLogo size={28} /></div>}
                <div style={{
                  maxWidth: "70%", padding: "10px 14px", borderRadius: 14,
                  background: msg.role === "user" ? "var(--green-700)" : "#fff",
                  color: msg.role === "user" ? "#fff" : "var(--text-primary)",
                  border: msg.role === "user" ? "none" : "1px solid var(--gray-200)",
                  fontSize: 14, lineHeight: 1.55,
                  borderTopLeftRadius: msg.role === "laura" ? 4 : 14,
                  borderTopRightRadius: msg.role === "user" ? 4 : 14,
                }}>{msg.text}</div>
                {msg.role === "user" && <div className="avatar sm" style={{ background: "var(--gray-100)", color: "var(--gray-700)" }}>{user.initials}</div>}
              </div>
            ))}
            {loading && (
              <div style={{ display: "flex", gap: 12, marginBottom: 14 }}>
                <LoraaLogo size={28} />
                <div style={{ padding: "10px 14px", borderRadius: 14, background: "#fff", border: "1px solid var(--gray-200)", display: "flex", gap: 4 }}>
                  <Dot delay={0} /><Dot delay={150} /><Dot delay={300} />
                </div>
              </div>
            )}
          </div>
        )}

        {/* Chat input */}
        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "10px 14px", background: "#fff",
          border: "1px solid var(--gray-300)", borderRadius: 14,
          boxShadow: "var(--shadow-card)",
        }}>
          <Icon name="lightbulb" size={18} style={{ color: "var(--brand-700)" }} />
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
            placeholder="Ask Loraa about recipes, ingredients, nutrition, compliance, or QA…"
            style={{ flex: 1, border: 0, outline: 0, fontSize: 15, background: "transparent", padding: "8px 0" }}
          />
          <button className="btn primary sm" onClick={send} disabled={!query.trim() || loading} style={{ borderRadius: 10 }}>
            <Icon name="send" size={14} />
          </button>
        </div>

        {/* Suggestions */}
        {thread.length === 0 && (
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 14, justifyContent: "center" }}>
            {suggestions.map((s, i) => (
              <button key={i} className="chip" onClick={() => setQuery(s)}>
                <Icon name="message-circle" size={12} /> {s}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Loraa Features */}
      <div style={{ marginTop: 32 }}>
        <h2 className="section-title">Loraa Features</h2>
        <p className="section-sub" style={{ marginBottom: 18 }}>Explore all AI features Loraa offers.</p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
          {LAURA_FEATURES.map((f) => (
            <button key={f.id} className="card pad" onClick={() => f.to ? setPage(f.to) : toast(`${f.title} (demo)`)} style={{
              textAlign: "left", cursor: "pointer",
              transition: "border-color .12s ease, transform .12s ease, box-shadow .12s ease",
            }} onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--green-300)"; e.currentTarget.style.boxShadow = "var(--shadow-hover)"; e.currentTarget.style.transform = "translateY(-2px)"; }}
               onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--gray-200)"; e.currentTarget.style.boxShadow = "var(--shadow-card)"; e.currentTarget.style.transform = "none"; }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12, marginBottom: 10 }}>
                <div className="stat-icon brand" style={{ width: 44, height: 44, borderRadius: 11, flexShrink: 0 }}><Icon name={f.icon} size={20} /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4 }}>{f.title}</div>
                  <div className="muted" style={{ fontSize: 13, lineHeight: 1.5 }}>{f.desc}</div>
                </div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14, paddingTop: 12, borderTop: "1px solid var(--gray-100)" }}>
                <span className={`pill ${f.status.tone}`}>{f.status.label}</span>
                <Icon name="arrow-right" size={16} style={{ color: "var(--gray-500)" }} />
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function Dot({ delay }) {
  return <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--gray-400)", animation: `pulse 1.2s ease-in-out ${delay}ms infinite` }} />;
}
(function injectLoraaStyles() {
  if (document.getElementById("laura-styles")) return;
  const s = document.createElement("style"); s.id = "laura-styles";
  s.textContent = `@keyframes pulse { 0%, 80%, 100% { opacity: .3; transform: scale(.8); } 40% { opacity: 1; transform: scale(1.1); } }`;
  document.head.appendChild(s);
})();

// ───── QA Review ─────
function QAReviewScreen() {
  const { setPage, toast, openRecipe } = useApp();
  const [selectedRecipe, setSelectedRecipe] = React.useState(null);
  const [scanning, setScanning] = React.useState(null);

  // Synthetic QA data
  const qaItems = React.useMemo(() => {
    return RECIPES.slice(0, 8).map((r, i) => {
      const errs = i % 3 === 0 ? 12 : 0;
      const warns = !errs ? 4 : 0;
      return { ...r, errors: errs, warnings: warns };
    });
  }, []);

  const stats = {
    scanned: 390,
    passed: 283,
    critical: 29,
    warnings: 17,
  };

  const handleScan = (item) => {
    setScanning(item.id);
    setTimeout(() => {
      setScanning(null);
      toast(`Loraa scanned ${item.name}, 2 issues found`);
      setSelectedRecipe(item);
    }, 1400);
  };

  if (selectedRecipe) {
    return <QAReviewDetail recipe={selectedRecipe} onBack={() => setSelectedRecipe(null)} />;
  }

  return (
    <div>
      <Crumbs path={[{ label: "Dashboard", onClick: () => setPage("dashboard") }, { label: "QA review" }]} />
      <div className="page-head">
        <div>
          <h1 className="page-title">QA Review</h1>
          <p className="page-sub">Auto-detects errors, warnings, and compliance gaps across all recipe fields.</p>
        </div>
        <button className="btn primary" onClick={() => toast("Bulk scan started")}>
          <LoraaLogo size={16} /> Scan All with Loraa
        </button>
      </div>

      <div className="stats" style={{ gridTemplateColumns: "repeat(4, 1fr)", marginBottom: 22 }}>
        <IntStat label="Recipes Scanned" value={stats.scanned} icon="file-search" tone="info" />
        <IntStat label="Passed QA"        value={stats.passed}   icon="check-circle-2" tone="success" />
        <IntStat label="Critical Issues"  value={stats.critical} icon="alert-octagon"  tone="error" />
        <IntStat label="Warnings"         value={stats.warnings} icon="alert-triangle" tone="warn" />
      </div>

      <div className="card" style={{ padding: 18 }}>
        <div style={{ display: "flex", gap: 12, marginBottom: 14, alignItems: "center" }}>
          <div className="search" style={{ flex: 1 }}>
            <Icon name="search" size={16} />
            <input placeholder="Search recipe" />
          </div>
          <button className="btn secondary"><Icon name="sliders-horizontal" size={14} /> Filter</button>
        </div>

        <table className="table">
          <thead><tr>
            <th>Recipe</th>
            <th>Location</th>
            <th>Category</th>
            <th>Created</th>
            <th>Time spent</th>
            <th>Status</th>
            <th style={{ textAlign: "right" }}>Scanning options</th>
          </tr></thead>
          <tbody>
            {qaItems.map((r) => (
              <tr key={r.id}>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <div className="thumb sm" style={{ backgroundImage: `url("${r.cover}")` }} />
                    <div>
                      <div style={{ fontWeight: 600 }}>{r.name}</div>
                      <div className="muted" style={{ fontSize: 12 }}>by {r.contributor.name}</div>
                    </div>
                  </div>
                </td>
                <td><span className="muted">{r.region}</span></td>
                <td><span className="pill brand" style={{ textTransform: "lowercase" }}>{r.category}</span></td>
                <td>{formatDate(r.submitted)}</td>
                <td>{r.timeSpent}</td>
                <td>
                  {r.errors > 0
                    ? <span className="pill error">{r.errors} Errors</span>
                    : <span className="pill warning">{r.warnings} Warnings</span>}
                </td>
                <td style={{ textAlign: "right" }}>
                  <div style={{ display: "inline-flex", gap: 8 }}>
                    <button className="btn primary sm" onClick={() => setSelectedRecipe(r)}>Resolve Manually</button>
                    <button className="btn secondary sm" onClick={() => handleScan(r)} disabled={scanning === r.id}>
                      {scanning === r.id
                        ? <><Icon name="loader-2" size={14} className="spin" /> Scanning…</>
                        : <><LoraaLogo size={14} /> Scan with Loraa</>}
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function QAReviewDetail({ recipe, onBack }) {
  const { toast } = useApp();
  const [tab, setTab] = React.useState("ingredients");
  const [errorOpen, setErrorOpen] = React.useState(null);

  // Synthetic issues
  const ingredientIssues = {
    2: { kind: "warning", message: "Quantity ambiguous, '3 medium' should specify weight in grams (e.g. '3 medium / ~450g')." },
    5: { kind: "error",   message: "'Curry Powder' is too generic, Loraa needs specific spice ratios for accurate macro calculation." },
  };
  const ingredients = [
    { name: "Red Lentils",     qty: "2 cups, rinsed and drained" },
    { name: "Onion",           qty: "1 large, finely chopped" },
    { name: "Tomatoes",        qty: "3 medium, diced" },
    { name: "Garlic",          qty: "4 cloves, minced" },
    { name: "Vegetable Broth", qty: "4 cups" },
    { name: "Curry Powder",    qty: "2 tablespoons" },
    { name: "Coconut Milk",    qty: "1 can" },
    { name: "Salt",            qty: "to taste" },
  ];

  return (
    <div>
      <Crumbs path={[
        { label: "QA Review", onClick: onBack },
        { label: recipe.name }
      ]} />

      <div className="page-head" style={{ alignItems: "flex-start" }}>
        <div>
          <span className="pill error" style={{ marginBottom: 10 }}>
            <Icon name="alert-octagon" size={12} stroke={2.4} /> Error found: 4 issues found
          </span>
          <h1 className="page-title">{recipe.name}</h1>
          <p className="page-sub" style={{ fontStyle: "italic" }}>"{recipe.description}"</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn secondary" onClick={onBack}><Icon name="arrow-left" size={16} /> Back</button>
          <button className="btn primary" onClick={() => { toast("Rescanning with Loraa…"); }}>
            <LoraaLogo size={16} /> Rescan with Loraa
          </button>
        </div>
      </div>

      {/* Recipe Images */}
      <div style={{ marginBottom: 24 }}>
        <h2 className="section-title" style={{ marginBottom: 12 }}>Recipe Images</h2>
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16 }}>
          <div style={{ aspectRatio: "16/10", backgroundImage: `url("${recipe.cover}")`, backgroundSize: "cover", backgroundPosition: "center", borderRadius: 14, border: "1px solid var(--gray-200)" }} />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            {[1, 2, 3].map((i) => (
              <div key={i} style={{ aspectRatio: "1/1", backgroundImage: `url("${recipe.cover}&w=${300 + i * 50}")`, backgroundSize: "cover", backgroundPosition: "center", borderRadius: 12, border: "1px solid var(--gray-200)", gridColumn: i === 1 ? "1 / 3" : undefined, aspectRatio: i === 1 ? "16/9" : "1/1" }} />
            ))}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="tabs" style={{ marginBottom: 16 }}>
        <button className={tab === "ingredients" ? "on" : ""} onClick={() => setTab("ingredients")}>
          Ingredients <span className="pill error" style={{ marginLeft: 6, fontSize: 11 }}>2</span>
        </button>
        <button className={tab === "method" ? "on" : ""} onClick={() => setTab("method")}>
          Method <span className="pill warning" style={{ marginLeft: 6, fontSize: 11 }}>1</span>
        </button>
        <button className={tab === "nutrition" ? "on" : ""} onClick={() => setTab("nutrition")}>
          Nutrition <span className="pill error" style={{ marginLeft: 6, fontSize: 11 }}>1</span>
        </button>
      </div>

      {tab === "ingredients" && (
        <div className="card" style={{ overflow: "hidden" }}>
          {ingredients.map((ing, i) => {
            const issue = ingredientIssues[i];
            const hasError = issue?.kind === "error";
            const hasWarn = issue?.kind === "warning";
            return (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 16,
                padding: "16px 20px",
                borderBottom: i < ingredients.length - 1 ? "1px solid var(--gray-100)" : "none",
                background: hasError ? "var(--error-50)" : hasWarn ? "var(--warning-50)" : "transparent",
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 8,
                  background: hasError ? "var(--error-100)" : hasWarn ? "var(--warning-100)" : "var(--gray-100)",
                  color: hasError ? "var(--error-600)" : hasWarn ? "var(--warning-600)" : "var(--gray-600)",
                  display: "grid", placeItems: "center", fontWeight: 700, fontSize: 13,
                }}>{i + 1}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, color: hasError ? "var(--error-600)" : "var(--text-primary)" }}>{ing.name}</div>
                  <div className="muted" style={{ fontSize: 13 }}>{ing.qty}</div>
                </div>
                {issue && (
                  <button className="btn secondary sm" onClick={() => setErrorOpen({ ...issue, name: ing.name, index: i })} style={{
                    color: hasError ? "var(--error-600)" : "var(--warning-600)",
                    borderColor: hasError ? "#FECDCA" : "#FEDF89",
                  }}>
                    <Icon name="eye" size={14} /> View Error
                  </button>
                )}
              </div>
            );
          })}
        </div>
      )}

      {tab === "method" && (
        <div className="card pad">
          <p className="muted">Method steps with inline issue annotations.</p>
          <div style={{ marginTop: 12 }}>
            <div style={{ padding: 16, background: "var(--warning-50)", borderRadius: 10, border: "1px solid #FEDF89" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
                <div>
                  <strong>Step 3:</strong> "Add curry powder and cook for 30 seconds."
                  <div style={{ color: "var(--warning-700)", fontSize: 13, marginTop: 6 }}>
                    <Icon name="alert-triangle" size={13} stroke={2.4} /> Loraa: temperature is ambiguous, specify heat level (low/medium/high) for reproducibility.
                  </div>
                </div>
                <button className="btn secondary sm">Fix</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {tab === "nutrition" && (
        <div className="card pad">
          <div className="alert error" style={{ marginBottom: 14 }}>
            <Icon name="alert-octagon" size={18} />
            <div>
              <strong>Calorie mismatch.</strong>
              <div style={{ marginTop: 2 }}>Calculated macros suggest ~520 kcal but recipe is tagged at {recipe.calories} kcal. Re-run macros against ingredient list.</div>
            </div>
            <button className="btn primary sm" style={{ marginLeft: "auto" }}>Auto-fix</button>
          </div>
        </div>
      )}

      {/* View Error modal */}
      <Modal open={!!errorOpen} onClose={() => setErrorOpen(null)} title="Issue detail" subtitle={errorOpen ? `Row ${errorOpen.index + 1} · ${errorOpen.name}` : ""} footer={
        <>
          <button className="btn ghost" onClick={() => setErrorOpen(null)}>Cancel</button>
          <button className="btn secondary" onClick={() => { setErrorOpen(null); toast("Manually edited"); }}><Icon name="pencil" size={14} /> Edit manually</button>
          <button className="btn primary" onClick={() => { setErrorOpen(null); toast("Loraa applied auto-fix"); }}><LoraaLogo size={14} /> Apply Loraa fix</button>
        </>
      }>
        {errorOpen && (
          <div className="col" style={{ gap: 14 }}>
            <div className={`alert ${errorOpen.kind === "error" ? "error" : "warning"}`}>
              <Icon name={errorOpen.kind === "error" ? "alert-octagon" : "alert-triangle"} size={18} />
              <div>{errorOpen.message}</div>
            </div>
            <div className="field">
              <label>Suggested fix (Loraa)</label>
              <div className="card" style={{ padding: 14, background: "var(--green-50)", border: "1px solid var(--green-200)" }}>
                <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                  <LoraaLogo size={20} />
                  <div style={{ fontSize: 14, lineHeight: 1.5, color: "var(--green-900)" }}>
                    {errorOpen.kind === "error"
                      ? `Replace "${errorOpen.name}" with "Garam Masala (1 tsp) + Cumin (1 tsp) + Turmeric (½ tsp)" for accurate macro calculation.`
                      : `Add weight in grams: "3 medium tomatoes (~450g)", this aligns with USDA macro tables.`}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

// ───── Workflow Automation ─────
function WorkflowAutomationScreen() {
  const { setPage, toast } = useApp();
  const [tab, setTab] = React.useState("all");
  const [createOpen, setCreateOpen] = React.useState(false);
  const [reportOpen, setReportOpen] = React.useState(null);

  const tasks = [
    { who: "Amaka Kennedy", initials: "AK", color: "#175CD3", role: "Media Contributor", progress: "12/20 (60%)", due: "Due May 10, 2026",       state: "in-progress", title: "20 Recipe assigned for image upload",  integration: "clickup" },
    { who: "Maria Chen",    initials: "MC", color: "#6938EF", role: "Media Contributor", progress: "20/20 (100%)", due: "Completed May 6, 2026", state: "completed",   title: "20 Recipe assigned for image upload",  integration: "clickup" },
    { who: "Uyieme Effiong",initials: "UE", color: "#0E9384", role: "Dietitian",         progress: "12/20 (60%)", due: "Passed May 2, 2026",      state: "overdue",     title: "Review 20 Beverage recipe",             integration: "asana" },
    { who: "John Doe",      initials: "JD", color: "#EA670C", role: "Media Contributor", progress: "20/20 (100%)", due: "Completed May 6, 2026", state: "completed",   title: "20 Recipe assigned for image upload",  integration: "clickup" },
    { who: "Richard Lois",  initials: "RL", color: "#3b7c0f", role: "Compliance",        progress: "12/20 (60%)", due: "Due May 10, 2026",       state: "in-progress", title: "20 Missing Nutrition Data for Recipe",  integration: "clickup" },
    { who: "Walter Barry",  initials: "WB", color: "#7F56D9", role: "Compliance",        progress: "12/20 (60%)", due: "Passed May 2, 2026",      state: "overdue",     title: "20 Missing Nutrition Data for Recipe",  integration: "asana" },
    { who: "Tamara Lois",   initials: "TL", color: "#9AB3FF", role: "Dietitian",         progress: "20/20 (100%)", due: "Completed May 6, 2026", state: "completed",   title: "Review 20 Beverage recipe",              integration: "clickup" },
  ];

  const filtered = tasks.filter((t) =>
    tab === "all" ? true :
    tab === "in-progress" ? t.state === "in-progress" :
    tab === "completed"   ? t.state === "completed" :
    tab === "overdue"     ? t.state === "overdue" : true
  );
  const counts = {
    all: tasks.length,
    "in-progress": tasks.filter(t => t.state === "in-progress").length,
    "completed":   tasks.filter(t => t.state === "completed").length,
    "overdue":     tasks.filter(t => t.state === "overdue").length,
  };

  return (
    <div>
      <Crumbs path={[{ label: "Dashboard", onClick: () => setPage("dashboard") }, { label: "Automation" }, { label: "Saved WorkFlow" }]} />
      <div className="page-head">
        <div>
          <h1 className="page-title">WorkFlow Automation</h1>
          <p className="page-sub">Real-time task tracking and workflow health across all automations.</p>
        </div>
        <button className="btn primary" onClick={() => setCreateOpen(true)}><Icon name="plus" size={16} /> Create WorkFlow</button>
      </div>

      {/* Stats with colored top border */}
      <div className="card" style={{ padding: 18, marginBottom: 22 }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
          <WfStat color="var(--success-500)" pill="Running"   pillTone="success" value="8"   label="Active workflows" sub="7 total assignees" />
          <WfStat color="#2A54E5"             pill="In progress" pillTone="info"    value="3"   label="Tasks In Progress" sub="7 total assignees" />
          <WfStat color="var(--green-700)"   pill="On Track"  pillTone="brand"   value="25%" label="Tasks on track" sub="2 of 8 task done on time" />
          <WfStat color="var(--error-500)"   pill="Over Due"  pillTone="error"   value="2"   label="Task Over Due"  sub="Passed due date" />
        </div>
      </div>

      {/* Task Activity */}
      <div className="section-head" style={{ margin: "8px 0 14px" }}>
        <div>
          <h2 className="section-title">Task Activity</h2>
        </div>
        <button className="btn secondary sm"><Icon name="sliders-horizontal" size={14} /> Filter</button>
      </div>

      <div className="tabs" style={{ marginBottom: 14 }}>
        {[
          { id: "all", label: "All" },
          { id: "in-progress", label: "In Progress" },
          { id: "completed", label: "Completed" },
          { id: "overdue", label: "Overdue" },
        ].map((t) => (
          <button key={t.id} className={tab === t.id ? "on" : ""} onClick={() => setTab(t.id)}>
            {t.label} <span style={{ marginLeft: 6, fontSize: 11, padding: "1px 7px", borderRadius: 999, background: tab === t.id ? "var(--green-100)" : "var(--gray-100)", color: tab === t.id ? "var(--green-700)" : "var(--gray-600)", fontWeight: 700 }}>{counts[t.id]}</span>
          </button>
        ))}
      </div>

      <div className="col" style={{ gap: 10 }}>
        {filtered.map((t, i) => (
          <div key={i} className="card" style={{ padding: 16, display: "flex", alignItems: "center", gap: 14 }}>
            <div className="avatar" style={{ background: t.color, width: 40, height: 40 }}>{t.initials}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 14, marginBottom: 2 }}>
                <strong>{t.who}</strong>
                <span className="muted" style={{ fontSize: 12 }}>•</span>
                <span className="muted" style={{ fontSize: 12 }}>{t.role}</span>
                <span className="muted" style={{ fontSize: 12 }}>•</span>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{t.progress}</span>
                <span className="muted" style={{ fontSize: 12 }}>•</span>
                {t.state === "overdue" && <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--error-600)", fontSize: 12, fontWeight: 600 }}><Icon name="clock" size={12} /> {t.due}</span>}
                {t.state === "completed" && <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--success-600)", fontSize: 12, fontWeight: 600 }}><Icon name="clock" size={12} /> {t.due}</span>}
                {t.state === "in-progress" && <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--gray-600)", fontSize: 12, fontWeight: 500 }}><Icon name="clock" size={12} /> {t.due}</span>}
              </div>
              <div style={{ fontSize: 14, color: "var(--gray-700)" }}>{t.title}</div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span className="pill info" style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <BrandLogo brand={t.integration} color={t.integration === "clickup" ? "#7B68EE" : "#F06A6A"} name={t.integration} size={16} /> {t.integration === "clickup" ? "Clickup" : "Asana"}
              </span>
              {t.state === "in-progress" && <span className="pill info">In progress</span>}
              {t.state === "completed"   && <span className="pill success">Completed</span>}
              {t.state === "overdue"     && <span className="pill error">Over Due</span>}
              <button className="icon-btn" onClick={() => setReportOpen(t)} title="Report"><Icon name="more-vertical" size={16} /></button>
            </div>
          </div>
        ))}
      </div>

      <Modal open={createOpen} onClose={() => setCreateOpen(false)} title="Create WorkFlow" subtitle="Define a trigger, assignee, and integration." footer={
        <>
          <button className="btn ghost" onClick={() => setCreateOpen(false)}>Cancel</button>
          <button className="btn primary" onClick={() => { setCreateOpen(false); toast("Workflow created"); }}><Icon name="zap" size={14} /> Create</button>
        </>
      } width={620}>
        <div className="col" style={{ gap: 14 }}>
          <div className="field">
            <label>Workflow name</label>
            <input className="input" placeholder="e.g. Image upload assignments" />
          </div>
          <div className="field">
            <label>Trigger</label>
            <select className="select"><option>When a recipe is submitted</option><option>When QA review fails</option><option>When a recipe is approved</option><option>Scheduled (weekly)</option></select>
          </div>
          <div className="field">
            <label>Assign to</label>
            <select className="select"><option>Media Contributors (any)</option><option>Dietitian on duty</option><option>Compliance team</option><option>Specific user…</option></select>
          </div>
          <div className="field">
            <label>Send to integration</label>
            <div style={{ display: "flex", gap: 8 }}>
              <button className="chip on"><BrandLogo brand="clickup" color="#7B68EE" name="ClickUp" size={16} /> ClickUp</button>
              <button className="chip"><BrandLogo brand="asana" color="#F06A6A" name="Asana" size={16} /> Asana</button>
              <button className="chip"><BrandLogo brand="trello" color="#0079BF" name="Trello" size={16} /> Trello</button>
            </div>
          </div>
        </div>
      </Modal>

      <Modal open={!!reportOpen} onClose={() => setReportOpen(null)} title="" footer={
        <>
          <button className="btn secondary" onClick={() => setReportOpen(null)}>Cancel</button>
          <button className="btn danger" onClick={() => { setReportOpen(null); toast("Report sent to Admin"); }}><Icon name="send" size={14} /> Submit Report</button>
        </>
      } width={500}>
        <div style={{ marginBottom: 14 }}>
          <div className="stat-icon error" style={{ width: 44, height: 44, borderRadius: 12 }}><Icon name="alert-triangle" size={20} /></div>
        </div>
        <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 10 }}>Send a report message or note to Admin</div>
        <textarea className="textarea" rows="5" placeholder="Type message here" />
      </Modal>
    </div>
  );
}

function WfStat({ color, pill, pillTone, value, label, sub }) {
  return (
    <div style={{ paddingTop: 12, borderTop: `3px solid ${color}` }}>
      <span className={`pill ${pillTone}`}>{pill}</span>
      <div style={{ fontSize: 32, fontWeight: 700, marginTop: 8, letterSpacing: "-.02em" }}>{value}</div>
      <div style={{ fontWeight: 600, fontSize: 14, marginTop: 2 }}>{label}</div>
      <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{sub}</div>
    </div>
  );
}

// ───── Audit Log v2 (with Custom Fix / Loraa Fix stats + Decline Fix modal) ─────
function LegacyAuditLogV2Unavailable() {
  const { setPage, toast } = useApp();
  const [items, setItems] = React.useState([]);
  const [declineOpen, setDeclineOpen] = React.useState(null);
  const [declineNote, setDeclineNote] = React.useState("");
  const [declineError, setDeclineError] = React.useState(false);
  const [liveTick, setLiveTick] = React.useState(0);

  // Live system events (deletes, restores, purges, role changes…) from the
  // append-only audit store, refreshed whenever a new event is recorded.
  React.useEffect(() => {
    const h = () => setLiveTick((t) => t + 1);
    window.addEventListener("nutridms-audit", h);
    window.addEventListener("focus", h);
    return () => { window.removeEventListener("nutridms-audit", h); window.removeEventListener("focus", h); };
  }, []);

  const ACTION_LABEL = {
    "item.deleted": "Moved to Recycle Bin", "item.restored": "Restored from Recycle Bin",
    "item.purged": "Permanently deleted", "bin.auto_purged": "Auto-purged (retention)",
    "bin.emptied": "Recycle Bin emptied", "role.assigned": "Role assigned",
    "rule.updated": "Compliance rule updated", "workflow.updated": "Workflow updated",
  };
  const ACTION_ICON = {
    "item.deleted": "trash-2", "item.restored": "rotate-ccw", "item.purged": "trash",
    "bin.auto_purged": "clock", "bin.emptied": "trash", "role.assigned": "user-cog",
  };
  const live = React.useMemo(() => {
    const raw = [];
    return raw.map((e, idx) => {
      // target looks like: "recipe · Tandoori Chicken (NUTRI-000022) → Recycle Bin"
      const t = e.target || "";
      const m = t.match(/^(\w+)\s·\s(.+?)(?:\s\(([^)]+)\))?(?:\s→\s(.+))?$/);
      const kindStr = m ? m[1] : "";
      const name = m ? m[2] : t;
      const ref = m ? m[3] : "";
      const dest = m ? m[4] : "";
      return {
        id: "sys-" + idx + "-" + e.when, kind: "system", when: e.when,
        recipe: name || "—", field: (kindStr ? kindStr[0].toUpperCase() + kindStr.slice(1) + " · " : "") + (ACTION_LABEL[e.action] || e.action),
        ref, dest, action: e.action, icon: ACTION_ICON[e.action] || "shield",
        actor: e.who || "System", severity: e.severity || "low", note: t,
      };
    });
  }, [liveTick]);

  const fixes = items.map((i) => ({ ...i, kind: "fix" }));
  const merged = React.useMemo(() => [...live, ...fixes].sort((a, b) => String(b.when).localeCompare(String(a.when))), [live, items]);

  const counts = {
    total: merged.length,
    custom: items.filter((i) => i.source === "custom").length,
    laura:  items.filter((i) => i.source === "laura").length,
  };

  const exportCsv = () => {
    const cols = ["Timestamp", "Item / Field", "Change", "Source", "Actor", "Status"];
    const esc = (v) => `"${String(v == null ? "" : v).replace(/"/g, '""')}"`;
    const rows = merged.map((i) => i.kind === "system"
      ? [i.when, `${i.recipe}, ${i.field}`, [i.ref, i.dest].filter(Boolean).join(" "), "System", i.actor, i.severity].map(esc).join(",")
      : [i.when, `${i.recipe}, ${i.field}`, `${i.before} → ${i.after}`, i.source, i.actor, i.status].map(esc).join(","));
    const csv = [cols.map(esc).join(","), ...rows].join("\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = `nutridms-audit-log-${new Date().toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
    toast(`Exported ${merged.length} audit entr${merged.length === 1 ? "y" : "ies"}`);
  };

  const accept = (id) => {
    setItems((prev) => prev.map((i) => i.id === id ? { ...i, status: "accepted" } : i));
    toast("Fix accepted");
  };
  const startDecline = (item) => { setDeclineOpen(item); setDeclineNote(""); setDeclineError(false); };
  const submitDecline = () => {
    if (!declineNote.trim()) { setDeclineError(true); return; }
    setItems((prev) => prev.map((i) => i.id === declineOpen.id ? { ...i, status: "declined", note: declineNote } : i));
    setDeclineOpen(null);
    toast("Fix declined with audit note");
  };

  return (
    <div>
      <Crumbs path={[{ label: "Dashboard", onClick: () => setPage("dashboard") }, { label: "Audit log" }]} />
      <div className="page-head">
        <div>
          <h1 className="page-title">Audit Log</h1>
          <p className="page-sub">Track all Loraa and edited scans for recipes, ingredients, allergens and more.</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn secondary" onClick={exportCsv}><Icon name="download" size={16} /> Export CSV</button>
          <button className="btn primary" onClick={() => setPage("qa-review")}><LoraaLogo size={16} /> Scan with Loraa</button>
        </div>
      </div>

      <div className="stats" style={{ gridTemplateColumns: "repeat(3, 1fr)", marginBottom: 22 }}>
        <IntStat label="Total Audit Logs" value={counts.total}  icon="history"  tone="error" />
        <IntStat label="Custom Fix"       value={counts.custom} icon="pencil"   tone="success" />
        <div className="stat" style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ width: 56, height: 56, borderRadius: 14, background: "linear-gradient(135deg, #E3FBCC, #C7D7FE)", display: "grid", placeItems: "center", flexShrink: 0 }}>
            <LoraaLogo size={28} />
          </div>
          <div>
            <div className="muted" style={{ fontSize: 13, fontWeight: 500, marginBottom: 2 }}>Loraa Fix</div>
            <div className="stat-value" style={{ fontSize: 32 }}>{counts.laura}</div>
          </div>
        </div>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <table className="table">
          <thead><tr>
            <th>Timestamp</th>
            <th>Recipe / Field</th>
            <th>Change</th>
            <th>Source</th>
            <th>Actor</th>
            <th>Status</th>
            <th style={{ textAlign: "right" }}>Action</th>
          </tr></thead>
          <tbody>
            {merged.map((i) => i.kind === "system" ? (
              <tr key={i.id}>
                <td style={{ fontFamily: "monospace", fontSize: 12, color: "var(--gray-600)" }}>{i.when}</td>
                <td>
                  <div style={{ fontWeight: 600 }}>{i.recipe}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{i.field}</div>
                </td>
                <td style={{ maxWidth: 280 }}>
                  {i.ref && <span className="ref-badge" style={{ marginRight: 6 }}><Icon name="hash" size={11} stroke={2.4} /><span className="ref-badge-num">{i.ref}</span></span>}
                  {i.dest && <span style={{ fontSize: 13, color: "var(--text-primary)", fontWeight: 600 }}>{i.dest}</span>}
                  {!i.ref && !i.dest && <span style={{ fontSize: 13, color: "var(--gray-500)" }}>—</span>}
                </td>
                <td>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name={i.icon} size={14} style={{ color: "var(--gray-500)" }} /> System</span>
                </td>
                <td>{i.actor}</td>
                <td>
                  {i.severity === "high" && <span className="pill error"><Icon name="shield-alert" size={11} stroke={2.4} /> Permanent</span>}
                  {i.severity === "medium" && <span className="pill warning"><Icon name="check" size={11} stroke={2.4} /> Recorded</span>}
                  {i.severity === "low" && <span className="pill neutral"><Icon name="check" size={11} stroke={2.4} /> Recorded</span>}
                </td>
                <td style={{ textAlign: "right" }}>
                  <button className="icon-btn" title={i.note}><Icon name="info" size={16} /></button>
                </td>
              </tr>
            ) : (
              <tr key={i.id}>
                <td style={{ fontFamily: "monospace", fontSize: 12, color: "var(--gray-600)" }}>{i.when}</td>
                <td>
                  <div style={{ fontWeight: 600 }}>{i.recipe}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{i.field}</div>
                </td>
                <td style={{ maxWidth: 280 }}>
                  <div style={{ fontSize: 13, color: "var(--gray-600)", textDecoration: "line-through" }}>{i.before}</div>
                  <div style={{ fontSize: 13, color: "var(--text-primary)", fontWeight: 600 }}>{i.after}</div>
                </td>
                <td>
                  {i.source === "laura"
                    ? <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><LoraaLogo size={14} /> Loraa</span>
                    : <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="pencil" size={14} style={{ color: "var(--success-600)" }} /> Custom</span>}
                </td>
                <td>{i.actor}</td>
                <td>
                  {i.status === "accepted" && <span className="pill success"><Icon name="check" size={11} stroke={2.4} /> Accepted</span>}
                  {i.status === "declined" && <span className="pill error">Declined</span>}
                  {i.status === "pending"  && <span className="pill warning">Pending</span>}
                </td>
                <td style={{ textAlign: "right" }}>
                  {i.status === "pending" && (
                    <div style={{ display: "inline-flex", gap: 6 }}>
                      <button className="btn primary sm" onClick={() => accept(i.id)}><Icon name="check" size={14} /> Accept</button>
                      <button className="btn secondary sm" onClick={() => startDecline(i)}><Icon name="x" size={14} /> Decline</button>
                    </div>
                  )}
                  {i.status !== "pending" && (
                    <button className="icon-btn" title={i.note}><Icon name="info" size={16} /></button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <Modal open={!!declineOpen} onClose={() => setDeclineOpen(null)} title="Decline Fix" subtitle={declineOpen ? `${declineOpen.recipe} · ${declineOpen.field}` : ""} footer={
        <>
          <button className="btn secondary" onClick={() => setDeclineOpen(null)}>Cancel</button>
          <button className="btn danger" onClick={submitDecline}><Icon name="send" size={14} /> Submit reason</button>
        </>
      }>
        {declineError && (
          <div className="alert error" style={{ marginBottom: 14 }}>
            <Icon name="alert-triangle" size={18} />
            <div>
              <strong>Please Note!</strong>
              <div style={{ marginTop: 2 }}>You must enter an audit note to state why you are declining this fix.</div>
            </div>
          </div>
        )}
        <div className="field">
          <label>Add an Audit note</label>
          <textarea className="textarea" rows="4" value={declineNote} onChange={(e) => { setDeclineNote(e.target.value); setDeclineError(false); }} placeholder="Type message here" />
        </div>
      </Modal>
    </div>
  );
}

Object.assign(window, { LoraaLogo, AskLoraaScreen, QAReviewScreen, WorkflowAutomationScreen });
