%% Week 5 Challenge (Starter) — Labor Market Equilibrium (Exogenous Wage)
% Goal: Solve Z(h) = 0 for h in (0,1)
% Methods: (i) Bisection, (ii) Damped Newton
% Then: comparative statics over tau in [0, 0.4]
%
% Instructions:
% - Complete all TODO blocks.
% - Keep code tidy and comment each step.
% - Report: h*, iterations, |Z(h*)| for each method.
% - Plot h*(tau) at the end.

clear; clc; close all;

%% --- PARAMETERS (calibrated for interior root ~0.47-0.48) ---
w     = 1.0;     % exogenous wage
tau   = 0.20;    % tax rate
a     = 0.50;    % lump-sum transfer
g     = 0.00;    % government spending (ignored in c here)
sigma = 2.0;     % CRRA coefficient
phi   = 2.0;     % leisure curvature
chi   = 3.7;     % weight on disutility of work

% Domain for h
h_low  = 1e-6;
h_high = 1 - 1e-6;

%% --- MODEL OBJECTS ---
% Budget (short run): c(h) = (1 - tau) * w * h + a - g
c  = @(h) (1 - tau) * w .* h + a - g;

% First-order condition in root-finding form:
% U_c(c(h)) * (1 - tau) * w - V_l(1 - h) = 0
% with U_c(c) = c^(-sigma), V_l(ell) = chi * ell^phi
Z=[] %% <--- TO DO 

% (Optional) Quick endpoint check — expect sign change on (0,1)
Zlow  = Z(h_low);
Zhigh = Z(h_high);
fprintf('Z at endpoints: Z(%.1e)=%.3f, Z(1-%.1e)=%.3f\n', h_low, Zlow, 1-h_high, Zhigh);

%% ========= PART 1A: BISECTION METHOD (fill in) =========
tol   = 1e-8;
maxit = 100;

%% TODO:
% 1) Initialize low/high = h_low / h_high
% 2) Implement bisection loop:
%    - mid = (low+high)/2
%    - If |Z(mid)| < tol or (high-low) < tol, stop
%    - If Z(low)*Z(mid) < 0, high = mid; else low = mid
% 3) Set h_bis = mid, store iteration count in it_bis
% 4) Print result: h_bis, |Z(h_bis)|, it_bis


%% ========= PART 1B: DAMPED NEWTON (fill in) =========
% Hint: use a finite-difference derivative for Z at point x:
fd = @(f,x) (f(x + 1e-6) - f(x - 1e-6)) / (2e-6);

alpha_step = 0.5;   % damping in (0,1]
h0 = 0.50;          % good initial guess inside (0,1)

% TODO:
% 1) Initialize h = h0
% 2) For it = 1:maxit:
%    - Zh  = Z(h)
%    - dZh = fd(Z, h)   (guard against very small |dZh|)
%    - h   = h - alpha_step * Zh / dZh
%    - Project: h = min(max(h, h_low), h_high)
%    - Stop if |Zh| < tol
% 3) Set h_new = h, store iteration count in it_new
% 4) Print result: h_new, |Z(h_new)|, it_new


%% ========= PART 2: COMPARATIVE STATICS IN tau (fill in) =========
taus = linspace(0, 0.4, 9);
H_tau = nan(size(taus));

%% TODO:
% For each tau value:
%   - Rebuild c(h) and Z(h) with current tau
%   - Solve Z(h)=0 by Bisection (robust) reusing the same tol/maxit
%   - Store solution in H_tau(j)
% Finally: plot taus vs H_tau

%% TODO: Inspect Z(h) for all values of h =========
