// ARS — Services & Pricing section (with admin inline editing)
const { useState: useStateSvc } = React;

function PriceRow({ children, last }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14,
      padding: "13px 0", borderBottom: last ? "none" : "1px solid var(--line)" }}>
      {children}
    </div>
  );
}

/* ---- one editable line item (string or grip) ---- */
function ItemLine({ item, editing, onChange, onRemove, last }) {
  return (
    <PriceRow last={last}>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontWeight: 700, fontSize: 15.5, color: "var(--ink)" }}>
          <EditText value={item.name} editing={editing} bold onChange={(v) => onChange({ ...item, name: v })}
            placeholder="String name" style={{ width: editing ? "100%" : "auto", maxWidth: 230 }} />
        </div>
        <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: editing ? 6 : 2 }}>
          <EditText value={item.detail} editing={editing} onChange={(v) => onChange({ ...item, detail: v })}
            placeholder="color · gauge" style={{ width: editing ? "100%" : "auto", maxWidth: 230, fontSize: 13 }} />
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <PriceTag value={item.price} editing={editing} onChange={(v) => onChange({ ...item, price: v })} />
        {editing && (
          <button onClick={onRemove} title="Remove" style={{ color: "#c0413a", display: "flex", padding: 4 }}>
            <Icon name="trash" size={18} />
          </button>
        )}
      </div>
    </PriceRow>
  );
}

/* ---- category card for strings / grips ---- */
function CategoryCard({ cat, editing, onUpdate, accent }) {
  const setItem = (it) => onUpdate({ ...cat, items: cat.items.map((x) => (x.id === it.id ? it : x)) });
  const removeItem = (id) => onUpdate({ ...cat, items: cat.items.filter((x) => x.id !== id) });
  const addItem = () => onUpdate({ ...cat, items: [...cat.items, { id: window.ARS.uid("n"), name: "", detail: "", price: 10 }] });
  return (
    <div className="card" style={{ padding: "24px 24px 18px", display: "flex", flexDirection: "column",
      boxShadow: "var(--shadow)", borderTop: `5px solid ${accent}` }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 4 }}>
        <h3 style={{ fontSize: 21, color: "var(--navy)" }}>
          <EditText value={cat.category} editing={editing} bold onChange={(v) => onUpdate({ ...cat, category: v })} placeholder="Category" />
        </h3>
        <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: accent }}>{cat.blurb}</span>
      </div>
      <div style={{ marginTop: 8 }}>
        {cat.items.map((it, i) => (
          <ItemLine key={it.id} item={it} editing={editing} last={i === cat.items.length - 1 && !editing}
            onChange={setItem} onRemove={() => removeItem(it.id)} />
        ))}
      </div>
      {editing && (
        <button onClick={addItem} className="btn btn-sm" style={{ marginTop: 14, alignSelf: "flex-start",
          background: "var(--green-soft)", color: "var(--green-deep)" }}>
          <Icon name="plus" size={15} stroke={3} /> Add string
        </button>
      )}
    </div>
  );
}

const SERVICE_TABS = [
  { id: "labor", label: "Stringing Labor" },
  { id: "strings", label: "Strings" },
  { id: "extras", label: "Grips & Add-ons" },
];

function Services({ data, setData, editing, onBook }) {
  const [tab, setTab] = useStateSvc("labor");
  const PRINT = !!window.__PRINT__;
  const sectLabel = (txt) => PRINT ? <h3 className="display" style={{ fontSize: 26, color: "var(--navy)", margin: "34px 0 16px" }}>{txt}</h3> : null;

  const updateList = (key, idx, patch) => {
    const next = window.ARS.deepClone(data);
    next[key][idx] = { ...next[key][idx], ...patch };
    setData(next);
  };
  const updateCat = (key, catId, newCat) => {
    const next = window.ARS.deepClone(data);
    next[key] = next[key].map((c) => (c.id === catId ? newCat : c));
    setData(next);
  };

  return (
    <section id="services" className="section" style={{ background: "var(--white)" }}>
      <div className="wrap">
        <div style={{ display: "flex", flexWrap: "wrap", gap: 20, alignItems: "flex-end", justifyContent: "space-between", marginBottom: 34 }}>
          <Heading eyebrow="Services & Pricing" title="Pick your service" sub="Transparent, racquet-by-racquet pricing. No surprises, no shop markup." />
          <button className="btn btn-green" onClick={onBook}><Icon name="calendar" size={18} /> Book this</button>
        </div>

        {/* tabs */}
        {!PRINT && <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 34 }}>
          {SERVICE_TABS.map((t) => {
            const on = tab === t.id;
            return (
              <button key={t.id} onClick={() => setTab(t.id)} className="btn"
                style={{ background: on ? "var(--navy)" : "#fff", color: on ? "#fff" : "var(--navy)",
                  border: on ? "2px solid var(--navy)" : "2px solid var(--line)", padding: "11px 22px" }}>
                {t.label}
              </button>
            );
          })}
          {editing && <span style={{ alignSelf: "center", marginLeft: 6, fontWeight: 800, fontSize: 13,
            color: "var(--green-deep)", display: "inline-flex", gap: 7, alignItems: "center" }}>
            <Icon name="edit" size={15} /> Editing live — changes save automatically</span>}
        </div>}

        {/* LABOR */}
        {sectLabel("Stringing Labor")}
        {(tab === "labor" || PRINT) && (
          <div style={{ display: "grid", gap: 24, gridTemplateColumns: "repeat(auto-fit,minmax(280px,1fr))" }}>
            <div className="card" style={{ padding: 26, boxShadow: "var(--shadow)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                <span style={{ color: "var(--green)" }}><Icon name="racquet" size={22} /></span>
                <h3 style={{ fontSize: 20, color: "var(--navy)" }}>Stringing Labor</h3>
              </div>
              {data.labor.map((it, i) => (
                <PriceRow key={it.id} last={i === data.labor.length - 1}>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 15.5 }}>{it.name}</div>
                    <div style={{ fontSize: 13, color: "var(--ink-2)" }}>{it.desc}</div>
                  </div>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 6, whiteSpace: "nowrap" }}>
                    <PriceTag value={it.price} editing={editing} free={false} onChange={(v) => updateList("labor", i, { price: v })} />
                    <span style={{ fontSize: 12, color: "var(--ink-2)", fontWeight: 600 }}>{it.unit}</span>
                  </div>
                </PriceRow>
              ))}
            </div>
            <div className="card" style={{ padding: 26, boxShadow: "var(--shadow)", background: "var(--navy)", color: "#fff", borderColor: "var(--navy)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                <span style={{ color: "var(--ball)" }}><Icon name="bolt" size={22} /></span>
                <h3 style={{ fontSize: 20, color: "#fff" }}>Add-on Fees</h3>
              </div>
              {data.fees.map((it, i) => (
                <div key={it.id} style={{ display: "flex", justifyContent: "space-between", gap: 14, padding: "13px 0",
                  borderBottom: i === data.fees.length - 1 ? "none" : "1px solid rgba(255,255,255,.14)" }}>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 15.5 }}>{it.name}</div>
                    <div style={{ fontSize: 13, color: "rgba(255,255,255,.65)" }}>{it.desc}</div>
                  </div>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 6, whiteSpace: "nowrap" }}>
                    {editing ? <PriceTag value={it.price} editing free={false} onChange={(v) => updateList("fees", i, { price: v })} />
                      : <span style={{ fontWeight: 800, color: "var(--ball)" }}>+${it.price}</span>}
                    <span style={{ fontSize: 12, color: "rgba(255,255,255,.6)", fontWeight: 600 }}>{it.unit}</span>
                  </div>
                </div>
              ))}
              <p style={{ fontSize: 13, color: "rgba(255,255,255,.6)", marginTop: 16, marginBottom: 0 }}>
                Custom hybrids & special-order strings available — just ask (48-hour turnaround).
              </p>
            </div>
          </div>
        )}

        {/* STRINGS */}
        {sectLabel("Strings")}
        {(tab === "strings" || PRINT) && (
          <div style={{ display: "grid", gap: 24, gridTemplateColumns: "repeat(auto-fit,minmax(290px,1fr))" }}>
            {data.strings.map((cat, i) => (
              <CategoryCard key={cat.id} cat={cat} editing={editing} accent={["var(--green)", "var(--navy)", "var(--ball-deep)"][i % 3]}
                onUpdate={(c) => updateCat("strings", cat.id, c)} />
            ))}
          </div>
        )}

        {/* EXTRAS: grips + other labor */}
        {sectLabel("Grips & Add-ons")}
        {(tab === "extras" || PRINT) && (
          <div style={{ display: "grid", gap: 24, gridTemplateColumns: "repeat(auto-fit,minmax(290px,1fr))" }}>
            {data.grips.map((cat, i) => (
              <CategoryCard key={cat.id} cat={cat} editing={editing} accent={["var(--green)", "var(--navy)"][i % 2]}
                onUpdate={(c) => updateCat("grips", cat.id, c)} />
            ))}
            <div className="card" style={{ padding: "24px 24px 18px", boxShadow: "var(--shadow)", borderTop: "5px solid var(--ball-deep)" }}>
              <h3 style={{ fontSize: 21, color: "var(--navy)", marginBottom: 8 }}>Other Labor</h3>
              {data.otherLabor.map((it, i) => (
                <PriceRow key={it.id} last={i === data.otherLabor.length - 1 && !editing}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 15.5 }}>
                      <EditText value={it.name} editing={editing} bold onChange={(v) => updateList("otherLabor", i, { name: v })} placeholder="Service" />
                    </div>
                    {it.desc && !editing && <div style={{ fontSize: 13, color: "var(--ink-2)" }}>{it.desc}</div>}
                  </div>
                  <PriceTag value={it.price} editing={editing} onChange={(v) => updateList("otherLabor", i, { price: v })} />
                </PriceRow>
              ))}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

window.Services = Services;
