// =========================================================
//   DOUGH RECIPE TAB
//   Recipes are NOT stored in this file. They live on the
//   Worker and are fetched only after login (password sent
//   in the X-App-Password header), so the recipe text is
//   never shipped in the public front-end source.
// =========================================================

function WaterTicks({ id, total, chunk, label, compact, theme, checks, setChecks }) {
  const count = Math.max(1, Math.round(total / chunk));
  const current = checks[id] || [];
  const toggle = (i) => {
    const next = [...current];
    next[i] = !next[i];
    setChecks({ ...checks, [id]: next });
  };
  const done = current.filter(Boolean).length;
  return (
    <div style={{
      background: theme.row, border: `1px solid ${theme.accent}`,
      borderRadius: 12, padding: "12px 14px", margin: "4px 0 10px",
    }}>
      <div style={{
        fontSize: 12, fontWeight: 700, color: theme.accent,
        textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8,
        display: "flex", justifyContent: "space-between", alignItems: "center"
      }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>{Icon.drop(13)} {label}</span>
        <span style={{ color: theme.muted, fontSize: 11 }}>{done}/{count}</span>
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {Array.from({ length: count }).map((_, i) => {
          const on = !!current[i];
          const labelText = compact
            ? (total >= 1 ? `${total}L` : `${Math.round(total * 1000)}ml`)
            : `${chunk}L`;
          return (
            <button key={i} onClick={() => toggle(i)} style={{
              flex: 1, minWidth: 80, padding: "10px 8px", borderRadius: 10,
              border: `2px solid ${on ? theme.accent : theme.checkBorder}`,
              background: on ? theme.accent : "transparent",
              color: on ? theme.accentText : theme.text,
              cursor: "pointer", display: "flex", alignItems: "center",
              justifyContent: "center", gap: 6, fontWeight: 700, fontSize: 15
            }}>
              {on && Icon.check(14)} {labelText}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function RecipeStep({ step, idx, theme }) {
  const stepText = step.text;
  return (
    <div style={{
      display: "flex", gap: 12, padding: "10px 0",
      borderTop: `1px solid ${theme.rowBorder}`
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: 999, flexShrink: 0,
        background: theme.accent, color: theme.accentText,
        display: "flex", alignItems: "center", justifyContent: "center",
        fontWeight: 700, fontSize: 13
      }}>{idx}</div>
      <div style={{ flex: 1, fontSize: 15, lineHeight: 1.45, color: theme.text, paddingTop: 3 }}>
        {stepText}
      </div>
    </div>
  );
}

// Fetch recipes from the Worker using a dough password. Returns the list or
// throws. The password is checked on the server, so editing the browser does
// not help anyone who does not know it.
async function fetchDough(doughPw) {
  const base = getWorkerBase();
  if (!base) throw new Error("No server configured.");
  const res = await fetch(`${base}/dough`, {
    headers: { "X-Dough-Password": doughPw }
  });
  if (res.status === 401) throw new Error("Wrong dough password.");
  if (!res.ok) throw new Error(`Couldn't load recipes (HTTP ${res.status}).`);
  const data = await res.json();
  return Array.isArray(data.recipes) ? data.recipes : [];
}

function DoughTab({ theme, goHome }) {
  const [recipes, setRecipes] = useState(null);   // null = locked / not loaded
  const [error, setError] = useState("");
  const [pwInput, setPwInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [activeId, setActiveId] = useLocal("fs.dough.active.v1", "");
  const [checks, setChecks] = useLocal("fs.dough.checks.v1", {});

  const loadWith = async (doughPw) => {
    setLoading(true);
    setError("");
    try {
      const list = await fetchDough(doughPw);
      // Remember the dough password in memory only for this session, so
      // leaving and returning to the tab does not re-prompt. Never stored.
      window.FS_SESSION = window.FS_SESSION || {};
      window.FS_SESSION.doughPw = doughPw;
      setRecipes(list);
      if (list.length) setActiveId(prev => prev || list[0].id);
    } catch (e) {
      setRecipes(null);
      setError(e.message || "Couldn't load recipes.");
      if (window.FS_SESSION) window.FS_SESSION.doughPw = "";
    } finally {
      setLoading(false);
    }
  };

  // If the dough password was already entered this session, auto-load.
  useEffect(() => {
    const saved = (window.FS_SESSION && window.FS_SESSION.doughPw) || "";
    if (saved) loadWith(saved);
  }, []);

  const submitPw = () => {
    const pw = pwInput.trim();
    if (!pw) { setError("Enter the dough password"); return; }
    loadWith(pw);
  };

  const recipe = recipes ? (recipes.find(r => r.id === activeId) || recipes[0]) : null;

  const clearRecipe = () => {
    if (!recipe) return;
    const next = { ...checks };
    recipe.steps.forEach(s => { if (s.kind === "waterCheck") delete next[s.id]; });
    setChecks(next);
  };

  let stepNum = 0;

  return (
    <div style={{ display: "flex", flexDirection: "column", flex: 1, minHeight: 0 }}>
      <PageHeader title="Dough Recipes" onBack={goHome} theme={theme} />
      <div style={{ padding: "14px 20px 28px", overflowY: "auto", flex: 1 }}>

        {recipes === null && (
          <div style={{ maxWidth: 320, margin: "30px auto 0", textAlign: "center" }}>
            <div style={{ display: "flex", justifyContent: "center", color: theme.accent, marginBottom: 12 }}>{Icon.lock(30)}</div>
            <div style={{ fontSize: 15, fontWeight: 600, color: theme.text, marginBottom: 6 }}>
              Recipes are locked
            </div>
            <div style={{ fontSize: 13, color: theme.muted, marginBottom: 16, lineHeight: 1.5 }}>
              Enter the head chef dough password to view the recipes.
            </div>
            <input
              type="password"
              value={pwInput}
              onChange={e => setPwInput(e.target.value)}
              onKeyDown={e => e.key === "Enter" && submitPw()}
              placeholder="Dough password"
              style={{
                width: "100%", padding: "12px 14px", borderRadius: 10,
                border: `1px solid ${theme.rowBorder}`, background: theme.input,
                color: theme.text, fontSize: 15, fontFamily: "inherit",
                outline: "none", marginBottom: 10, textAlign: "center"
              }}
            />
            <button onClick={submitPw} disabled={loading} style={{
              ...primaryBtn(theme), opacity: loading ? 0.6 : 1,
              cursor: loading ? "wait" : "pointer"
            }}>
              {loading ? "Checking…" : "Unlock recipes"}
            </button>
            {error && (
              <div style={{ color: theme.danger || "#c8413a", fontSize: 13, fontWeight: 600, marginTop: 12 }}>
                {error}
              </div>
            )}
          </div>
        )}

        {recipes && recipe && (
          <>
            {/* Recipe switcher */}
            <div style={{
              display: "flex", gap: 8, padding: 4, background: theme.row,
              border: `1px solid ${theme.rowBorder}`, borderRadius: 12, marginBottom: 18
            }}>
              {recipes.map(r => {
                const on = r.id === recipe.id;
                return (
                  <button key={r.id} onClick={() => setActiveId(r.id)} style={{
                    flex: 1, padding: "10px 8px", borderRadius: 9, border: "none",
                    background: on ? theme.accent : "transparent",
                    color: on ? theme.accentText : theme.text,
                    fontWeight: 700, fontSize: 14, cursor: "pointer"
                  }}>{r.name}</button>
                );
              })}
            </div>

            {/* Header card */}
            <div style={{
              padding: "14px 16px", borderRadius: 12, marginBottom: 14,
              background: theme.row, border: `1px solid ${theme.rowBorder}`
            }}>
              <div style={{ fontSize: 20, fontWeight: 700, color: theme.text, marginBottom: 4 }}>
                {recipe.name}
              </div>
              <div style={{ fontSize: 13, color: theme.muted, marginBottom: 6 }}>
                {recipe.subtitle}
              </div>
              <div style={{ fontSize: 12, color: theme.accent, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase" }}>
                Yield · {recipe.yield}
              </div>
            </div>

            {/* Steps */}
            <div>
              {recipe.steps.map((s, i) => {
                if (s.kind === "heading") {
                  return (
                    <div key={i} style={{
                      fontSize: 12, fontWeight: 700, color: theme.accent,
                      textTransform: "uppercase", letterSpacing: "0.12em",
                      marginTop: 18, marginBottom: 8, paddingBottom: 6,
                      borderBottom: `1px solid ${theme.accent}`
                    }}>{s.text}</div>
                  );
                }
                if (s.kind === "note") {
                  return (
                    <div key={i} style={{
                      margin: "6px 0 10px", padding: "10px 14px", borderRadius: 10,
                      background: `${theme.accent}22`, border: `1px dashed ${theme.accent}`,
                      fontSize: 13, fontStyle: "italic", color: theme.text
                    }}>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>{Icon.alert(13)} {s.text}</span>
                    </div>
                  );
                }
                if (s.kind === "waterCheck") {
                  return <WaterTicks key={i} {...s}
                    theme={theme} checks={checks} setChecks={setChecks}/>;
                }
                stepNum++;
                return <RecipeStep key={i} step={s} idx={stepNum} theme={theme}/>;
              })}
            </div>

            <div style={{ height: 22 }}/>
            <button onClick={clearRecipe} style={ghostBtn(theme)}>Reset water ticks</button>
          </>
        )}
      </div>
    </div>
  );
}
