/* General Contracting — Trade leaf-menu page */

const TOP5 = [
  {
    rank: 1,
    title: "How to hire a good general contractor",
    why: "References, insurance, contract terms. The non-negotiables when handing someone the keys.",
    img: "https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?w=1400&q=80",
    time: "Hiring",
    cost: "10-20% of budget",
    slot: "feature",
  },
  {
    rank: 2,
    title: "How to pull a building permit",
    why: "What the city actually requires, where to file, what the inspector looks for.",
    img: "https://images.unsplash.com/photo-1552664730-d307ca884978?w=1000&q=80",
    time: "Varies",
    cost: "$50–$500+",
    slot: "small s-1",
  },
  {
    rank: 3,
    title: "How to write a renovation scope of work",
    why: "Room-by-room specs, material callouts. The document contractors bid from.",
    img: "https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?w=1000&q=80",
    time: "Prep",
    cost: "Your time",
    slot: "small s-2",
  },
  {
    rank: 4,
    title: "How to pay a contractor without getting burned",
    why: "Draw schedule, lien waivers, retainage. The mechanics of leverage.",
    img: "https://images.unsplash.com/photo-1552664730-d307ca884978?w=1200&q=80",
    time: "Ongoing",
    cost: "Key process",
    slot: "wide",
  },
  {
    rank: 5,
    title: "How to be your own general contractor",
    why: "Pull permits, hire subs, manage timeline. Save 10–20% but costs 100+ hours.",
    img: "https://images.unsplash.com/photo-1543269865-cbdf26cecb46?w=1000&q=80",
    time: "Full project",
    cost: "Your labor",
    slot: "right2",
  },
];

const HOWTOS = [
  // Hiring
  { cat: "hiring", title: "How to hire a good general contractor", desc: "References, insurance, contract terms. The non-negotiables.", time: "Hiring", unit: "Prep", level: 2, tags: ["Hiring", "Vetting"] },
  { cat: "hiring", title: "How to vet a contractor before signing", desc: "Background check, license, insurance, references, site visits.", time: "1–2 weeks", unit: "Timeline", level: 2, tags: ["Vetting", "Contracts"] },

  // Permits
  { cat: "permits", title: "How to pull a building permit", desc: "City requirements, filing, timing, inspector relationships.", time: "1–4 weeks", unit: "Varies", level: 3, tags: ["Permits", "Admin"] },
  { cat: "permits", title: "GC safety and permit checklist", desc: "Site safety, OSHA basics, permit compliance, inspection prep.", time: "Daily", unit: "Checklist", level: 1, tags: ["Safety", "Compliance"] },

  // Planning
  { cat: "planning", title: "How to write a renovation scope of work", desc: "Room-by-room specs, material callouts, fixture details.", time: "2–4 hours", unit: "Document", level: 2, tags: ["Planning", "Documentation"] },
  { cat: "planning", title: "How to handle change orders", desc: "Scope creep protocol, signed changes, cost and timeline impact.", time: "Per change", unit: "Process", level: 2, tags: ["Management", "Changes"] },

  // Money
  { cat: "money", title: "How to pay a contractor without getting burned", desc: "Draw schedule, lien waivers, retainage, leverage mechanics.", time: "Ongoing", unit: "Process", level: 2, tags: ["Money", "Protection"] },
  { cat: "money", title: "How to protect yourself with a mechanic's lien waiver", desc: "Conditional vs unconditional, timing, what they protect.", time: "Each payment", unit: "1 page", level: 1, tags: ["Legal", "Protection"] },

  // DIY & Survival
  { cat: "diy", title: "How to be your own general contractor", desc: "Pulling permits, hiring subs, timeline management, coordination.", time: "Full project", unit: "DIY", level: 4, tags: ["DIY GC", "Advanced"] },
  { cat: "diy", title: "How to survive a six-week renovation living in the house", desc: "Daily routines, dust containment, shower access, mental health.", time: "Daily", unit: "Survival", level: 1, tags: ["Living in reno", "Practical"] },
  { cat: "diy", title: "How to deal with a failed inspection", desc: "Why inspectors fail work, reading violations, negotiating fixes.", time: "1–3 days", unit: "Per failure", level: 2, tags: ["Inspection", "Recovery"] },

  // Budgeting
  { cat: "budget", title: "How to budget a kitchen renovation", desc: "Cabinetry, counters, appliances, plumbing, electrical, labor, contingency.", time: "Planning", unit: "Budget", level: 2, tags: ["Kitchen", "Budgeting"] },
  { cat: "budget", title: "How to budget a bathroom renovation", desc: "Fixtures, tile, ventilation, plumbing, electrical, contingency breakdown.", time: "Planning", unit: "Budget", level: 2, tags: ["Bathroom", "Budgeting"] },
];

const CATS = [
  { id: "all",       label: "All guides" },
  { id: "hiring",    label: "Hiring & vetting" },
  { id: "permits",   label: "Permits & legal" },
  { id: "planning",  label: "Planning" },
  { id: "money",     label: "Money & protection" },
  { id: "diy",       label: "DIY & survival" },
  { id: "budget",    label: "Budgeting" },
];

const MISTAKES = [
  {
    title: "Paying too much money up front",
    body: "Contractors pressure for 50% down; you lose all leverage once the money's gone. Structure: 25% down (materials + mobilization), 50% at halfway point, 25% final (punch list complete).",
    fix: "Never pay more than 25% to start. Keep leverage until the work is done.",
  },
  {
    title: "Picking the lowest bid",
    body: "The cheapest quote is usually the path to a bad job, shortcuts, and callbacks. Check three bids; the middle one usually represents reality.",
    fix: "Compare scope, timeline, and reputation. Price is one factor, not the only one.",
  },
  {
    title: "No written scope of work",
    body: "Verbal agreements are forgotten at day 30. 'Build a bathroom' is fighting words. 'Remove vanity, relocate drain 18 inches, tile to code, install fixture set X' is a contract.",
    fix: "Write it room by room, every material called out. Both sign it. Reference it.",
  },
  {
    title: "No change-order process",
    body: "Scope creep is the default. Every change is free until you need to say no. Then it's war.",
    fix: "Every change must be signed, priced, and scheduled before work starts. Charge for them.",
  },
  {
    title: "Ignoring the inspector's notes",
    body: "Inspectors don't fail work for fun. A failed inspection means code violation, liability, resale risk. Reading the violation and fixing it right is the path forward.",
    fix: "Understand why they failed it. Fix it to code. Don't argue with the city; you'll lose.",
  },
  {
    title: "Hiring an unlicensed sub to save 15%",
    body: "The GC is liable for their work. If they get hurt, you're sued. If the work fails, you're sued. If there's a fire traced to bad wiring, you're sued.",
    fix: "Require license, insurance, and lien waiver. The 15% savings isn't worth the exposure.",
  },
];

const TOOLS = [
  { name: "Written scope of work", desc: "Room-by-room specs, material callouts, fixture details. The contract's spine.", cost: "Your time" },
  { name: "Payment schedule (25/50/25)", desc: "25% down, 50% at halfway, 25% final. Standard contractor draw structure.", cost: "Agreement" },
  { name: "Lien waivers (conditional & unconditional)", desc: "Proof that subs are paid. Require after each draw. Protects you from claims.", cost: "$0" },
  { name: "Schedule of values breakdown", desc: "Itemize the contract by phase so you know what 50% of work looks like.", cost: "Your time" },
  { name: "Punch list (final items)", desc: "Final list of incomplete or defective items, usually done 2–3 days before final payment.", cost: "Your time" },
  { name: "Certificate of insurance (every sub)", desc: "Proof they carry general liability. Minimum $1M. Protects you if they get hurt.", cost: "$0" },
  { name: "Permit copy & amendment sheets", desc: "Your protection with the city. Proof of what work is approved.", cost: "$0" },
  { name: "The 10–20% GC fee rule", desc: "GC overhead and profit. It's not free money; it's insurance against disaster and coordination.", cost: "Part of budget" },
];

const COLOR_PICKS = [
  { name: "Deep Walnut",    code: "HE-201", hex: "#3D2817" },
  { name: "Blueprint Cream", code: "HE-202", hex: "#E8DCC8" },
  { name: "Builder's Gray",  code: "HE-203", hex: "#5C5653" },
];

/* ---------- Components ---------- */

const Top5Card = ({ item }) => (
  <a className={`top5-card ${item.slot}`} href="#">
    <div className="img" style={{ backgroundImage: `url(${item.img})` }} />
    <span className="rank">{item.rank}</span>
    <div className="meta">
      <h3>{item.title}</h3>
      <p className="why">{item.why}</p>
      <div className="row">
        <span>{item.time}</span>
        <span>{item.cost}</span>
      </div>
    </div>
  </a>
);

const MenuRow = ({ guide, idx }) => (
  <a className="menu-row" href="#">
    <span className="num">№ {String(idx + 1).padStart(2, "0")}</span>
    <div className="title">
      <h4>{guide.title}</h4>
      <p className="desc">{guide.desc}</p>
    </div>
    <div className="tags">
      {guide.tags.map(t => <span key={t} className="tag">{t}</span>)}
    </div>
    <div className="duration">
      {guide.time}
      <span className="l">{guide.unit}</span>
    </div>
    <div className="level" data-level={guide.level >= 4 ? "hard" : "ok"}>
      {[1,2,3,4,5].map(i => (
        <span key={i} className={`pip ${i <= guide.level ? "on" : ""}`}></span>
      ))}
    </div>
    <div className="arrow">&rarr;</div>
  </a>
);

const Contracting = ({ category = "all", showMistakes = true, showTools = true, showColor = true }) => {
  const filtered = category === "all" ? HOWTOS : HOWTOS.filter(g => g.cat === category);
  return (
    <div className="contracting-page">
      {/* HERO */}
      <section className="contracting-hero">
        <div className="wrap-wide">
          <div className="crumbs">
            <a href="/">Home</a>
            <span className="sep">/</span>
            <a href="/en/trades/">Trades</a>
            <span className="sep">/</span>
            <span className="here">General Contracting</span>
          </div>

          <div className="contracting-hero-grid">
            <h1>Whole rooms, additions,<br/>anything that touches <em>three trades</em> and a permit.</h1>
            <div className="right-col">
              <p className="lede">
                This is project management, not a Saturday. Coordinate the subs, pull the permits, manage the timeline, hold everyone accountable. Hire one or be one.
              </p>
            </div>
          </div>

          <div className="contracting-stats">
            <div className="stat">
              <span className="n">{HOWTOS.length}</span>
              <span className="l">Guides in this trade</span>
            </div>
            <div className="stat">
              <span className="n"><em>10–20%</em></span>
              <span className="l">GC margin of total budget</span>
            </div>
            <div className="stat">
              <span className="n"><em>4–12 wks</em></span>
              <span className="l">Typical renovation timeline</span>
            </div>
            <div className="stat">
              <span className="n"><em>5<span style={{opacity:0.4}}>/5</span></em></span>
              <span className="l"><span className="dot">&bull;</span> DIY-ability</span>
            </div>
          </div>
        </div>
      </section>

      {/* TOP 5 */}
      <section className="contracting-top5">
        <div className="wrap-wide">
          <div className="lede-row">
            <div className="left">
              <span className="label">The Editor&rsquo;s 5</span>
              <h2>Five projects ranked <em>by coordination difficulty.</em></h2>
            </div>
            <div className="right">
              <p>These projects require a GC—either hired or playing the role yourself. Ranked by complexity, permits, and what happens if something goes wrong.</p>
            </div>
          </div>
          <div className="top5-grid">
            {TOP5.map(t => <Top5Card key={t.rank} item={t} />)}
          </div>
        </div>
      </section>

      {/* THE MENU */}
      <section className="contracting-menu">
        <div className="wrap-wide">
          <div className="menu-head">
            <h2>Every GC guide, <em>in one list.</em></h2>
            <span className="count">{filtered.length} of {HOWTOS.length} shown</span>
          </div>
          <div className="menu-tabs" role="tablist">
            {CATS.map(c => {
              const n = c.id === "all" ? HOWTOS.length : HOWTOS.filter(g => g.cat === c.id).length;
              return (
                <button key={c.id}
                  className={`menu-tab ${category === c.id ? "on" : ""}`}
                  onClick={() => window.__setContractingCategory && window.__setContractingCategory(c.id)}>
                  {c.label}<span className="num">{String(n).padStart(2,"0")}</span>
                </button>
              );
            })}
          </div>
          <div className="menu-list">
            {filtered.map((g, i) => <MenuRow key={g.title} guide={g} idx={i} />)}
          </div>
        </div>
      </section>

      {/* WHAT NOT TO DO */}
      {showMistakes && (
      <section className="contracting-mistakes">
        <div className="wrap-wide">
          <div className="mistakes-head">
            <span className="label">What not to do</span>
            <h2>Six mistakes <em>that haunt you.</em></h2>
            <p>Save yourself the lawyer fee — avoid these before they happen.</p>
          </div>
          <div className="mistakes-grid">
            {MISTAKES.map((m, i) => (
              <div className="mistake" key={m.title}>
                <div className="stamp">
                  <span className="x">&times;</span>
                  <span className="n">№ {String(i + 1).padStart(2,"0")}</span>
                </div>
                <div>
                  <h4>{m.title}</h4>
                  <p>{m.body}</p>
                  <div className="fix">{m.fix}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
      )}

      {/* TOOLS */}
      {showTools && (
      <section className="contracting-tools">
        <div className="wrap-wide tools-grid">
          <div className="left">
            <span className="label">The toolkit</span>
            <h2>Eight documents, <em>nothing more.</em></h2>
            <p>A good renovation runs on documents. Here's what you need to protect yourself and keep the job moving.</p>
            <div className="pull">
              &ldquo;10–20% of the total project budget goes to GC overhead and profit. Pretending otherwise gets you cut corners.&rdquo;
              <span className="src">&mdash; Marcus Webb, contractor</span>
            </div>
          </div>
          <div className="tool-list">
            {TOOLS.map((t, i) => (
              <div className="tool" key={t.name}>
                <span className="n">{String(i + 1).padStart(2,"0")}</span>
                <div>
                  <h5>{t.name}</h5>
                  <p className="desc">{t.desc}</p>
                </div>
                <span className="price">{t.cost}</span>
              </div>
            ))}
          </div>
        </div>
      </section>
      )}

      {/* COLOR / DETAIL MOMENT */}
      {showColor && (
      <section className="color-moment">
        <div className="wrap-wide color-moment-inner">
          <div>
            <span className="label">Design reality</span>
            <h2>The palette of <em>a good renovation.</em></h2>
            <p>Deep wood, parchment, and concrete. The colors of blueprints, permits, and work that lasts.</p>
            <div className="picks">
              {COLOR_PICKS.map(c => (
                <div className="color-pick" key={c.code}>
                  <div className="swatch" style={{ background: c.hex }}></div>
                  <div className="name">{c.name}</div>
                  <div className="code">{c.code}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="color-card">
            <div className="img" style={{ backgroundImage: "url(https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?w=1200&q=80)" }}/>
            <div className="stamp">The GC's workspace</div>
            <div className="badge">
              <div className="t">Scope · Timeline · Permits</div>
              <div className="m">COORDINATION · 10–20% OF BUDGET</div>
            </div>
          </div>
        </div>
      </section>
      )}
    </div>
  );
};

window.Contracting = Contracting;
