// screens-garage.jsx — Garage list + add/edit/delete car sheet.

const COLOR_PRESETS = [
  { name: "Silver", hex: "#c3c8cc" },
  { name: "Toffee Brown", hex: "#8a5a2b" },
  { name: "Black", hex: "#1c1f22" },
  { name: "White", hex: "#e9edf0" },
  { name: "Racing Red", hex: "#c4322f" },
  { name: "Blue", hex: "#2f5fc4" },
  { name: "British Green", hex: "#1f5a3d" },
  { name: "Graphite", hex: "#5e646b" },
  { name: "Sunburst", hex: "#e0a72e" },
  { name: "Orange", hex: "#d2622a" },
];
const EMOJI_OPTS = ["🚗", "🚙", "🚐", "🛻", "🏎️", "🏍️"];

function ScreenHeader({ title, subtitle, right }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", padding: "6px 2px 18px", gap: 12 }}>
      <div>
        <div style={{ fontSize: 33, fontWeight: 800, letterSpacing: -0.8, color: "var(--text)", lineHeight: 1.05 }}>{title}</div>
        {subtitle && <div style={{ fontSize: 14.5, color: "var(--text-2)", marginTop: 5, fontWeight: 500 }}>{subtitle}</div>}
      </div>
      {right}
    </div>
  );
}

function GarageScreen({ state, store }) {
  const [editing, setEditing] = React.useState(null); // car object or "new"
  const cars = state.cars;

  return (
    <div className="wmc-screen">
      <ScreenHeader
        title="Garage"
        subtitle={`${cars.length} ${cars.length === 1 ? "vehicle" : "vehicles"}`}
        right={<IconButton label="Add car" size={46} onClick={() => setEditing("new")} active style={{ borderRadius: "var(--radius-sm)" }}><IconPlus size={24} sw={2.2} /></IconButton>}
      />

      {cars.length === 0 ? (
        <EmptyState icon={<IconCar size={30} />} title="No cars yet"
          body="Add your first vehicle to start saving where you park."
          action={<AppButton icon={<IconPlus size={20} sw={2.2} />} onClick={() => setEditing("new")}>Add a car</AppButton>} />
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {cars.map((c) => (
            <CarRow key={c.id} car={c} store={store} onEdit={() => setEditing(c)} />
          ))}
        </div>
      )}

      <CarEditor
        open={!!editing}
        car={editing === "new" ? null : editing}
        store={store}
        canDelete={cars.length > 1}
        onClose={() => setEditing(null)}
      />
    </div>
  );
}

function CarRow({ car, store, onEdit }) {
  const Glyph = carGlyph(car.emoji);
  const parked = car.current;
  return (
    <Card pad={14} onClick={onEdit}>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{
          width: 52, height: 52, borderRadius: 14, background: car.color, color: pickInk(car.color),
          display: "grid", placeItems: "center", flexShrink: 0,
          boxShadow: "inset 0 0 0 1px rgba(255,255,255,.14), 0 2px 6px rgba(0,0,0,.25)",
        }}><Glyph size={28} sw={1.9} /></div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 17.5, fontWeight: 750, color: "var(--text)", letterSpacing: -0.2 }}>{car.name}</span>
            {car.isDefault && <span style={{
              fontSize: 10.5, fontWeight: 800, letterSpacing: 0.5, textTransform: "uppercase",
              color: "var(--accent-ink)", background: "var(--accent-soft)", padding: "2px 7px", borderRadius: 999,
            }}>Default</span>}
          </div>
          <div style={{ fontSize: 13.5, color: "var(--text-2)", marginTop: 3 }}>{car.colorName}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 7, fontSize: 13, fontWeight: 600, color: parked ? "var(--accent-ink)" : "var(--text-3)" }}>
            {parked ? <IconPin size={15} sw={2} /> : <IconPinPlus size={15} sw={2} />}
            {parked ? `Parked · ${relativeTime(parked.timestamp)}` : "Not parked"}
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8, flexShrink: 0 }} onClick={(e) => e.stopPropagation()}>
          <IconButton label={car.isDefault ? "Default car" : "Set as default"} size={38}
            active={car.isDefault} onClick={() => { store.setDefault(car.id); toast(`${car.name} is now your default`); }}
            style={{ color: car.isDefault ? "var(--on-accent)" : "var(--text-3)" }}>
            <IconStar size={19} filled={car.isDefault} />
          </IconButton>
          <span style={{ color: "var(--text-3)" }}><IconChevron size={18} /></span>
        </div>
      </div>
    </Card>
  );
}

function CarEditor({ open, car, store, canDelete, onClose }) {
  const isNew = !car;
  const [name, setName] = React.useState("");
  const [color, setColor] = React.useState(COLOR_PRESETS[0]);
  const [emoji, setEmoji] = React.useState("🚗");
  const [isDefault, setIsDefault] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    setConfirmDel(false);
    if (car) {
      setName(car.name);
      setColor({ name: car.colorName, hex: car.color });
      setEmoji(car.emoji || "🚗");
      setIsDefault(!!car.isDefault);
    } else {
      setName("");
      setColor(COLOR_PRESETS[0]);
      setEmoji("🚗");
      setIsDefault(false);
    }
  }, [open, car]);

  const save = () => {
    const clean = name.trim() || "My car";
    const payload = { name: clean, color: color.hex, colorName: color.name, emoji, isDefault };
    if (isNew) {
      const id = store.addCar(payload);
      if (isDefault) store.setDefault(id);
      toast("Car added");
    } else {
      store.updateCar(car.id, payload);
      if (isDefault && !car.isDefault) store.setDefault(car.id);
      toast("Saved");
    }
    onClose();
  };

  const del = () => {
    store.deleteCar(car.id);
    toast(`${car.name} removed`);
    onClose();
  };

  const Glyph = carGlyph(emoji);

  return (
    <Sheet open={open} onClose={onClose} title={isNew ? "Add a car" : "Edit car"}
      footer={
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <AppButton full onClick={save} icon={<IconCheck size={20} sw={2.3} />}>{isNew ? "Add car" : "Save changes"}</AppButton>
          {!isNew && canDelete && (
            confirmDel
              ? <AppButton full variant="danger" onClick={del} icon={<IconTrash size={19} />}>Delete {car.name} — tap to confirm</AppButton>
              : <AppButton full variant="ghost" onClick={() => setConfirmDel(true)} icon={<IconTrash size={19} />} style={{ color: "var(--danger)", boxShadow: "inset 0 0 0 1.5px var(--danger-bg)" }}>Delete car</AppButton>
          )}
        </div>
      }>
      {/* preview */}
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 20, padding: 14, borderRadius: "var(--radius)", background: "var(--surface-2)" }}>
        <div style={{ width: 54, height: 54, borderRadius: 14, background: color.hex, color: pickInk(color.hex), display: "grid", placeItems: "center", boxShadow: "inset 0 0 0 1px rgba(255,255,255,.14)" }}>
          <Glyph size={30} sw={1.9} />
        </div>
        <div>
          <div style={{ fontSize: 17, fontWeight: 750, color: "var(--text)" }}>{name.trim() || "My car"}</div>
          <div style={{ fontSize: 13.5, color: "var(--text-2)", marginTop: 2 }}>{color.name}</div>
        </div>
      </div>

      <Field label="NAME">
        <TextInput value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Audi A1" maxLength={28} />
      </Field>

      <Field label="TYPE">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 8 }}>
          {EMOJI_OPTS.map((e) => (
            <button key={e} className="wmc-btn" onClick={() => setEmoji(e)} style={{
              height: 48, borderRadius: "var(--radius-sm)", fontSize: 24, cursor: "pointer",
              border: emoji === e ? "1.5px solid var(--accent)" : "1.5px solid var(--hairline)",
              background: emoji === e ? "var(--accent-soft)" : "var(--surface-2)",
            }}>{e}</button>
          ))}
        </div>
      </Field>

      <Field label="COLOUR">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 10 }}>
          {COLOR_PRESETS.map((c) => {
            const on = c.hex === color.hex;
            return (
              <button key={c.hex} className="wmc-btn" title={c.name} onClick={() => setColor(c)} style={{
                aspectRatio: "1", borderRadius: 14, background: c.hex, cursor: "pointer", position: "relative",
                border: on ? "2.5px solid var(--accent)" : "2.5px solid transparent",
                boxShadow: "inset 0 0 0 1px rgba(255,255,255,.14)",
              }}>
                {on && <span style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", color: pickInk(c.hex) }}><IconCheck size={20} sw={2.6} /></span>}
              </button>
            );
          })}
        </div>
        <div style={{ marginTop: 10, fontSize: 13, color: "var(--text-2)", display: "flex", alignItems: "center", gap: 8 }}>
          <span>Name this colour</span>
          <input value={color.name} onChange={(e) => setColor({ ...color, name: e.target.value })}
            className="wmc-input" style={{ ...inputStyle, padding: "8px 11px", fontSize: 14, flex: 1 }} />
        </div>
      </Field>

      <button className="wmc-btn" onClick={() => setIsDefault((v) => !v)} style={{
        width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", cursor: "pointer",
        background: "var(--surface-2)", border: "1.5px solid var(--hairline)", borderRadius: "var(--radius-sm)",
        padding: "14px 15px", font: "inherit", color: "var(--text)", marginTop: 4,
      }}>
        <span style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 15.5, fontWeight: 600 }}>
          <IconStar size={19} filled={isDefault} style={{ color: isDefault ? "var(--accent)" : "var(--text-3)" }} />
          Set as default car
        </span>
        <span style={{
          width: 46, height: 28, borderRadius: 999, padding: 3, transition: "background .2s ease",
          background: isDefault ? "var(--accent)" : "var(--border-strong)", display: "flex",
        }}>
          <span style={{ width: 22, height: 22, borderRadius: 999, background: "#fff", transition: "transform .2s ease", transform: isDefault ? "translateX(18px)" : "translateX(0)" }} />
        </span>
      </button>
    </Sheet>
  );
}

Object.assign(window, { GarageScreen, CarEditor, ScreenHeader, COLOR_PRESETS, EMOJI_OPTS });
