/* eslint-disable no-undef */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* =========================================================
   Small visual atoms
   ========================================================= */

function Star({ filled, onClick, size = 30 }) {
  // Chunky 5-point star. Use a path that feels hand-cut, not generic 5-point math.
  return (
    <button
      className={"star-btn" + (filled ? " on" : "")}
      onClick={onClick}
      aria-label={filled ? "Filled star" : "Empty star"}
      type="button"
    >
      <svg viewBox="0 0 32 32" width={size} height={size}>
        <path
          className="fill"
          d="M16 2.6 l4.1 8.7 9.4 1.2 -6.9 6.6 1.8 9.4 -8.4-4.7 -8.4 4.7 1.8-9.4 -6.9-6.6 9.4-1.2 Z"
        />
        <path
          className="stroke"
          d="M16 2.6 l4.1 8.7 9.4 1.2 -6.9 6.6 1.8 9.4 -8.4-4.7 -8.4 4.7 1.8-9.4 -6.9-6.6 9.4-1.2 Z"
        />
      </svg>
    </button>
  );
}

function StarsInput({ value, onChange }) {
  return (
    <div className="stars" role="radiogroup" aria-label="Star rating">
      {[1,2,3,4,5].map(n => (
        <Star
          key={n}
          filled={n <= value}
          onClick={() => onChange(value === n ? 0 : n)}
        />
      ))}
    </div>
  );
}

function MiniStars({ value }) {
  if (!value) return null;
  return <span className="mini-stars">{"★".repeat(value)}{"☆".repeat(5 - value)}</span>;
}

function Badges({ gf, v, compact }) {
  if (!gf && !v) return null;
  return (
    <span className="flavor-badges">
      {gf && <span className="badge gf" title="Gluten Free">GF</span>}
      {v && <span className="badge v" title="Vegan">VG</span>}
    </span>
  );
}

function Avatar({ friend, size = 26 }) {
  if (!friend) return null;
  const initials = (friend.name || "?").trim().split(/\s+/).map(s => s[0]).slice(0,2).join("").toUpperCase() || "?";
  return (
    <span className="avatar" style={{ background: friend.color || "#FCD86A", width: size, height: size, fontSize: Math.round(size * 0.42) }}>
      {initials}
    </span>
  );
}

function Drip({ className }) {
  // hand-drawn pink drip ribbon similar to the poster corners
  return (
    <svg className={"title-drip " + (className || "")} viewBox="0 0 60 36">
      <g fill="none" stroke="#ee6388" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 4 q6 10 12 6 t14 8 t14 -4 t12 12" />
        <path d="M10 12 q3 6 0 14" />
        <path d="M30 18 q2 8 -2 14" />
        <path d="M48 14 q3 6 0 14" />
      </g>
      <g fill="#fcd86a" opacity="0.85">
        <circle cx="6" cy="4" r="2.3" />
        <circle cx="56" cy="4" r="2.3" />
      </g>
    </svg>
  );
}

/* =========================================================
   Flavor row inside the NOW card
   ========================================================= */

function FlavorRow({ flavor, log, onLogChange, toppingName, toppingTags, sprinklesAlways }) {
  // For the "now" card we let each friend pick which flavor(s) they got — so the
  // log isn't per-row. We just render the flavor info + badges here.
  return (
    <div className="flavor">
      <div className="flavor-head">
        <span className="flavor-name">{flavor.name}</span>
        <Badges gf={flavor.gf} v={flavor.v} />
      </div>
    </div>
  );
}

/* =========================================================
   Entry card — the per-friend logging form
   ========================================================= */

function EntryCard({ week, friend, entry, onChange, onDelete, onClose }) {
  const [draftComment, setDraftComment] = useState(entry?.comment || "");
  useEffect(() => { setDraftComment(entry?.comment || ""); }, [friend?.id, week.id]);

  const flavorIds = week.flavors.map(f => f.name);
  const got = entry?.flavors || [];

  const toggleFlavor = (name) => {
    const next = got.includes(name) ? got.filter(f => f !== name) : [...got, name];
    onChange({ ...entry, flavors: next });
  };

  return (
    <div className="entry-card scroll-anchor">
      <div className="who">
        <Avatar friend={friend} size={30} />
        <h4>{friend.name}'s pick</h4>
        <button className="close" onClick={onClose} aria-label="Close">×</button>
      </div>

      <div className="choice-row">
        <span className="row-label">Got which?</span>
        <div className="choice-group">
          {week.flavors.map(f => {
            const on = got.includes(f.name);
            return (
              <button
                key={f.name}
                className={"choice" + (on ? " selected pink" : "")}
                onClick={() => toggleFlavor(f.name)}
                type="button"
              >
                {f.name}
              </button>
            );
          })}
          <button
            className={"choice" + (got.length === 2 ? " selected pink" : "")}
            onClick={() => onChange({ ...entry, flavors: got.length === 2 ? [] : flavorIds })}
            type="button"
          >
            🍦 Both / swirl
          </button>
        </div>
      </div>

      <div className="choice-row">
        <span className="row-label">Topping?</span>
        <div className="choice-group">
          <button
            className={"choice" + (entry?.topping ? " selected" : "")}
            onClick={() => onChange({ ...entry, topping: !entry?.topping })}
            type="button"
          >
            {week.topping.name}
            {(week.topping.gf || week.topping.v) && (
              <span style={{ marginLeft: 6 }}>
                <Badges gf={week.topping.gf} v={week.topping.v} />
              </span>
            )}
          </button>
          <button
            className={"choice" + (entry?.sprinkles ? " selected" : "")}
            onClick={() => onChange({ ...entry, sprinkles: !entry?.sprinkles })}
            type="button"
          >
            🌈 Rainbow sprinkles
          </button>
        </div>
      </div>

      <div className="choice-row">
        <span className="row-label">How was it?</span>
        <StarsInput value={entry?.stars || 0} onChange={(stars) => onChange({ ...entry, stars })} />
      </div>

      <div className="choice-row">
        <span className="row-label">Note</span>
        <textarea
          className="comment-box"
          placeholder="A line or two…"
          value={draftComment}
          onChange={(e) => setDraftComment(e.target.value)}
          onBlur={() => onChange({ ...entry, comment: draftComment.trim() })}
          maxLength={240}
          rows={2}
        />
      </div>

      <div className="actions">
        <button className="btn-primary" onClick={() => { onChange({ ...entry, comment: draftComment.trim() }); onClose(); }}>
          Save
        </button>
        <button className="btn-danger" onClick={onDelete}>Delete</button>
      </div>
    </div>
  );
}

/* =========================================================
   Friend chip strip
   ========================================================= */

function FriendStrip({ friends, weekLogs, activeFriendId, onPickFriend, onManageFriends }) {
  return (
    <div className="friends-row">
      {friends.map(f => {
        const entry = weekLogs?.[f.id];
        const hasEntry = !!entry && (entry.flavors?.length || entry.stars || entry.comment || entry.topping || entry.sprinkles);
        return (
          <button
            key={f.id}
            className={"friend-chip" + (hasEntry ? " has-entry" : "") + (activeFriendId === f.id ? " active" : "")}
            onClick={() => onPickFriend(f.id)}
            type="button"
          >
            <Avatar friend={f} />
            <span>{f.name}</span>
            {hasEntry && entry.stars > 0 && <MiniStars value={entry.stars} />}
          </button>
        );
      })}
      <button className="friend-chip adding" onClick={onManageFriends} type="button">
        <span className="avatar" style={{ background: "transparent", border: "1.5px dashed currentColor", color: "var(--cream)" }}>+</span>
        <span>Edit crew</span>
      </button>
    </div>
  );
}

/* =========================================================
   Manage friends modal
   ========================================================= */

const FRIEND_COLORS = ["#FCD86A", "#EE6388", "#7EE0C5", "#FFB87A", "#C7B6FF", "#FF8DBE", "#9FE0FF", "#FFE08A"];

function ManageFriendsModal({ friends, onClose, onSave }) {
  const [list, setList] = useState(friends);
  const [newName, setNewName] = useState("");

  const update = (id, patch) => setList(list.map(f => f.id === id ? { ...f, ...patch } : f));
  const remove = (id) => setList(list.filter(f => f.id !== id));
  const add = () => {
    const name = newName.trim();
    if (!name) return;
    const usedColors = new Set(list.map(f => f.color));
    const color = FRIEND_COLORS.find(c => !usedColors.has(c)) || FRIEND_COLORS[list.length % FRIEND_COLORS.length];
    setList([...list, { id: "f_" + Date.now(), name, color }]);
    setNewName("");
  };

  return (
    <div className="modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal-sheet">
        <h3>Your softserve crew</h3>
        {list.map(f => (
          <div key={f.id} className="friend-edit-row">
            <Avatar friend={f} size={32} />
            <input
              value={f.name}
              onChange={(e) => update(f.id, { name: e.target.value })}
              maxLength={20}
            />
            <span className="swatches">
              {FRIEND_COLORS.map(c => (
                <button
                  key={c}
                  className={"swatch" + (f.color === c ? " on" : "")}
                  style={{ background: c }}
                  onClick={() => update(f.id, { color: c })}
                  type="button"
                  aria-label={"Use color " + c}
                />
              ))}
            </span>
            <button className="rm" onClick={() => remove(f.id)} aria-label="Remove">×</button>
          </div>
        ))}
        <div className="add-friend-row">
          <input
            placeholder="Add a friend…"
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") add(); }}
            maxLength={20}
          />
          <button onClick={add}>ADD</button>
        </div>
        <div className="actions" style={{ marginTop: 18, justifyContent: "flex-end" }}>
          <button
            className="btn-primary"
            style={{ fontFamily: "var(--f-display)", fontSize: 13, letterSpacing: 1.4, padding: "10px 18px", borderRadius: 999, background: "var(--pink)", color: "var(--cream)" }}
            onClick={() => { onSave(list); onClose(); }}
          >
            DONE
          </button>
        </div>
      </div>
    </div>
  );
}

/* =========================================================
   Week row in the season list
   ========================================================= */

function WeekRow({ week, isCurrent, isPast, friends, weekLogs, onTap }) {
  return (
    <div
      className={"week-row" + (isCurrent ? " is-current" : "") + (isPast ? " is-past" : "")}
      onClick={onTap}
      data-week={week.id}
    >
      <div className="wk-range">{week.range}</div>
      <div>
        <div className="wk-flavors-stack">
          {week.flavors.map((f, i) => (
            <div key={f.name} className="wk-flavor-line">
              <span>{f.name}</span>
              <Badges gf={f.gf} v={f.v} />
            </div>
          ))}
        </div>
        <div className="wk-topping">
          <span>+ topping</span>
          <b>{week.topping.name}</b>
          {(week.topping.gf || week.topping.v) && <Badges gf={week.topping.gf} v={week.topping.v} />}
        </div>
        {weekLogs && Object.keys(weekLogs).length > 0 && (
          <div className="wk-meta">
            {friends.map(f => {
              const e = weekLogs[f.id];
              if (!e || (!e.stars && !e.flavors?.length && !e.comment)) return null;
              return (
                <span key={f.id} className="wk-stamp">
                  <span className="av" style={{ background: f.color }}>{f.name[0].toUpperCase()}</span>
                  {e.stars > 0 && <span className="mini-stars">{"★".repeat(e.stars)}</span>}
                </span>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

/* expose to window for app.jsx */
Object.assign(window, {
  Star, StarsInput, MiniStars, Badges, Avatar, Drip,
  FlavorRow, EntryCard, FriendStrip, ManageFriendsModal, WeekRow,
  FRIEND_COLORS,
});
